console.log, values and types
Time for actual programming. JavaScript runs your code top to bottom, one statement at a time, and the easiest way to see what it is doing is console.log(), which prints whatever you hand it:
console.log("Hello!");
console.log(2 + 3);
Every piece of data in JavaScript is a value, and every value has a type. The three you will meet first:
- string: text, in quotes.
"pizza"or'pizza'both work. - number:
42,3.14,-7. No quotes. JavaScript does not split whole numbers and decimals into different types; they are all just numbers. - boolean: exactly two values,
trueandfalse. Used for yes or no questions.
Quotes change everything. 5 + 5 is 10, but "5" + "5" is "55", because + on strings glues them together (that is called concatenation). Mix a string and a number and JavaScript turns the number into text: "Level " + 3 gives "Level 3".
When you are not sure what something is, ask with typeof:
console.log(typeof 42); // number
console.log(typeof "42"); // string
console.log(typeof true); // boolean
The // starts a comment: JavaScript ignores the rest of that line. Semicolons end statements. JavaScript can often guess where they go, but writing them is a good habit.
Math works like you would expect: + - * /, plus % for the remainder after division (10 % 3 is 1). Brackets set the order, just like in maths class.
Try it yourself
Edit it. Break it. Run it again.console.log("Hello, world!");
console.log(7 * 6);
console.log("5" + "5");
console.log("Level " + 3);
console.log(10 % 3);
console.log(typeof 3.14, typeof "hi", typeof false);
Your turn
Type it yourself. That is the whole trick.1Two lines
Print exactly two lines: first the text Hello, JavaScript!, then the result of 12 * 4 (let JavaScript do the maths, do not type 48 yourself).
console.log("Hello");
2Spot the type
The code prints the types of three values but the values are wrong. Change the three values so the output is number, string, boolean on separate lines.
console.log(typeof "99"); console.log(typeof 99); console.log(typeof "true");