Conditional Operator
JavaScript supports conditional expression operator. They are? and :. These operators are ternary operators as they require three operands , a condition to be evaluated and the alternatives that need to be returned. The return value is based on the condition as it can be true or false.
Syntax:
variablename=(condition)?value1:value2
E.g.
result=(percentage==50)?"Pass":"Fail";
In the above example if the variable percentage has the value 50, then the variable result will be assigned the value “Pass” else it will be assigned "False".
6. Using + Operator with Strings
The + operator can be used to add string variables or text values together. In case operands are number + operator performs addition. In case operands are strings it is used to concatenate them.
E.g. Concatenating two Strings
t1="Welcome";
t2="India";
t3=t1+t2;
After the execution of the statements above, the variable t3 will contain the string “Welcome India”.
With + operator it is possible to concatenate two or more strings. You can even insert spaces and concatenate a string with a number.
E.g. To add a space between the two strings you can insert a space into one of the strings:
t1="Welcome";
t2="India";
t3=t1+” “ + t2;
After the execution of the statements above, the variable t3 contains string
"Welcome India
Note: If you add a number and a string, the result will be a string.
Check Your Progress
1. What do you understand by a block of code in JavaScript?
2 What are different data types available in JavaScript?
3. What are the different kinds of comments available in
JavaScript?
4. Give the output of the following code;
w=4;
y=++w;
z=w++;
document.write(w);
document.write(y);
document.write(z);
5. What is the use of conditional operator?
Comments