Exercises: JavaScript Variables
Standard Exercises
0. Write the following code into the console and run the code.
console.log("Hello");1. Print your name in the console using console.log().
2. What will the following print into the console? Type it in and try it out!
console.log(56*2);3. Print the number 47 using console.log().
4. Calculate 46+92 and print the result in the console.
5. Calculate 127/7.5 and print the result in the console.
6. Create a variable called ‘name’ and print that variable in the console. Test with the following code;
// Create variable name
console.log(name);7. Create the variable firstName and the variable lastName and print the two concatenated together.
8. Create the variable a = 10, print it, add 5 to it and print it again.
// create a
console.log(a);
// add 5 to a
console.log(a); 9. Some variables contain properties, which give you extra information about a variable. You access properties on a variable by using a '.' dot. Strings have a 'length' property. Complete the code below to print the length of the string.
var name = "John";
console.log( ... );10. You can use “+=” and “-=” as short-hand for “a = a + 1”. Convert the following to use += and -=.
var a = 10;
a = a + 5;
console.log(a);11. Create a constant variable using ‘const’ instead of 'var'. Try to change that variable on the line after and see what happens.
Advanced Exercises
12. Take a guess what value you get from these equations and then use the console to calculate it;
12 % 5
12 * 8 + 4 / 2
12 * (8 + 4) / 2
4 ** 2You can also use a++ and a-- to add/subtract one from a variable. Try out the following;
var a = 1;
console.log(a++);
console.log(a--);Wait - that's weird... It prints "1" and then "2"... What's going on (see the next question).
13. There are two ways to increment/decrement variables in JavaScript. The example shown above (a++) increments the variable and then returns the result. However, it's also possible to return the result and then increment the variable. This can lead to weird behaviour, so it's usually best to avoid it - but it can be useful in scenaroids. Try to figure out what is printed out on each line below, and then try it out!
var a = 1;
console.log(a++);
console.log(--a);
console.log(++a);
console.log(a--);
console.log(a);console.log("Hello World");