JavaScript Variables Worksheet
Snippet Expression Answer Explanation
1 100+4 104 basic addition
2 'a'+'b' 'ab' Concatenation of strings
3 'Bob'+'Smith' 'BobSmith' Concatenation of strings
4 '7'+'9' '79' Concatenation of strings
5 '7'+9 '79' Concatenation of strings, as JS treats the number like a string here
6 '7'-9 -2 Because the minus symbol is special to arithmetic functions, this treated as a numerical value
7 'abc'*3 NaN The multiplication operator wants to treat all parts of the expression as a number which is not possible - Not a Number
8 7+2*3 13 Order of operations
9 (7+2)*3 27 Order of operations
10 (null+2)/3 0.6666666666666666 Order of operations
"null" has no value, so evaluation continues after that expression
11 var name;
name
undefined The variable "name" holds no value
12 var x = 7;
var y = 4;
var z = x * y;
z-3
25 Logical math through use of variables
13 var a = true;
var b = false;
a && b
false Both condition must be met to be True
14 var a = true;
var b = false;
a || b
true If either condition is True, then the statement evaluates to True
15 var foo = 3;
foo++;
foo++;
foo/2
2.5 Variable "foo" is incremented two times and then divided
16 var age = 29.8;
var wholeAge = Math.floor(age);
var nextAge = Math.ceil(age);
nextAge - wholeAge
1 Variable age is rounded up then down to evaluate
17 '5' + 3 - 3 50 First part of expression is concatenated, then subtraction treats the expression as a number
18 var isRed = false;
isRed = !isRed;
isRed
true The use of the "!" (bang) character switches the value to the opposite
19 var isBlue = true;
var isBlue = !!isBlue;
isBlue
true Double bang makes the variable isBlue false and then true. Not extremely useful.
20 var name = 'Sally';
var age = 25;
name.length + age
30 Length of string added to a number
21 var x = 10;
var y = 73.3;
var point = '[' + x + ', ' + y + ']';
'point: '+point
'point: [10, 73.3]' Variables inserted into a string variable (that mimics an array)
22 var numberOfSheep = 16;
var numberOfGoats = 3;
numberOfGoats + numberOfSheep++
19 The evaluation of the values inside the variables occurs before the "++" increment expression can be stored and used
23 var numberOfSheep = 16;
var numberOfGoats = 3;
numberOfGoats - ++numberOfSheep
-14 The increment expression is before variable so it is evaluated before the numberOfSheep variable is already used
24 var x;
var y = (x=7);
y
7 Logical, just follow the parentheses