Lesson 2: Variables, Console, Comments
What did we talk about last lesson?
Number:
42
-3.1415
String:
"John"
'Berlin'
Boolean:
true
false
Undefined, no value:
undefined
- Create a new folder
- In that folder, create an html file:
index.html
<html>
<body>
<script src="main.js"></script>
</body>
</html>
- Also in that folder, create a JS file:
main.js
console.log("Hello from JavaScript");
- You can use
console.log
to print values to the console. - The console will only be visible to developers, not to the visitors of the website.
Example:
console.log("Hello");
console.log(3 * 4 + 5);
But with all these examples, we are just talking about data.
What if I wanted to save some data and use it later?
we use Variables
!
A pointer to some data or value.
let price = 5;
let name = "John";
let priceCoffee = 2;
let priceCappuccino = 3;
let customer = "John";
let company = undefined;
let greeting = "Hello";
let age = 50;
let hasKids = false;
Can you guess how can we create a variable?
We write:
let
- the variable name
=
- the value we want
;
What are the types of the following variables?
let temperature = 24;
let name = "John";
let teacherIsNice = true;
let totalPrice = '12.5';
let deliveryDate = undefined;
What are the types of the following variables?
let temperature = 24; // number
let name = "John"; // string
let teacherIsNice = true; // boolean
let totalPrice = '12.5'; // string
let deliveryDate = undefined; // undefined
Variables can also result from other variables!
let firstName = "John";
let lastName = "Smith";
let fullName = firstName + " " + lastName;
console.log("my full name is " + fullName);
// what is the output here?
// try it with your name!
You can name your variables whatever you want.
- You can use letters, numbers, and underscore _ (spaces are not allowed!)
- Variable name cannot start with a number.
Correct variable names:
let element = 3;
let element3 = 5;
Wrong variable names:
let 2squared = 4;
let element-1 = 0;
let full name = 'Anakin Skywalker';
Giving good and descriptive names to your variables is very important!
Good variable names make the code easier to understand by other developers, and even by yourself!
Not wrong but very bad variable names:
let a = 0;
let _12 = 0;
let asldjf = 0;
let thisisareallylongvariablename = 0;
In this course, and JavaScript in general, we use 'camelCase'
isStudent
favoriteFood
likesGermanFood
Variable names are case sensitive:
let name = 'John';
let Name = 'John';
let NAME = 'John';
These are 3 different variables.
When naming boolean variables, it is best to give it a name that describes a yes/no situation:
- isMarried
- hasKids
- canExecute
create 4 variables:
- one for your full name
- one for your age
- one for the city where you come from
- one for wether you can speak German or not
console.log()
all these variables!
You can write additional information in your code using comments.
Comments are completely ignored by JavaScript, they exist only to help developers.
// this is a single-line comment
// anything after // is ignored by JavaScript
let firstName = "John";
let age = 24; // I can also write a comment here!
/**
* this is a multi-line comment
*
* I can write however many lines I want!
*/
let lastName = "Smith";
JavaScript executes the code from top to bottom, line by line.
JavaScript will ignore comments.
Wrong:
console.log(name); // WRONG!! the variable "name" is not created!
let name = "Obi-Wan Kenobi";
Correct:
let name = "Obi-Wan Kenobi";
console.log(name); // correct!
3 + 4 // 7
3 - 4 // -1
3 * 4 // 12
3 / 4 // 0.75
"I live in" + " " + "Berlin"
// "I live in Berlin"
These and other operators also work on variables!
Convert Celsius to Fahrenheit.
let degreesInCelsius = 28;
// Fahrenheit = Celsius multiplied by 1.8 plus 32
let degreesInFahrenheit = ???;
// output to the console to see the final result
console.log(degreesInFahrenheit);
Convert Celsius to Fahrenheit.
let degreesInCelsius = 28;
// Fahrenheit = Celsius multiplied by 1.8 plus 32
let degreesInFahrenheit = degreesInCelsius * 1.8 + 32;
// output to the console to see the final result
console.log(degreesInFahrenheit); // 82.4
- What do you think
x
andy
are at the end of the program?
let x = 42;
let y = x;
x = 43;
console.log(x);
console.log(y);
Answer: x is 43, y is 42
- All basic data types (number, string, ...) are passed by value.
- If you assign a variable to another variable, its value is copied.
We can "chain" operators, for example:
1 + 2 + 3
(1 + 2) + 3 // same as above
(3) + 3 // returns 6
- Is the following code valid?
5 < 6 < 7
- Answer: It's valid JavaScript, but pointless
- Let's break it down:
5 < 6 < 7
(5 < 6) < 7 // 5 < 6 is true
true < 7 // pointless comparison!
- comparing a boolean to a number makes no sense. Don't chain comparison operators.
- What does the following return?
5 === 5 === 5
(5 === 5) === 5
true === 5 // returns false
What do you think is the result?
2 + 2 * 2
Result: 6
- JavaScript supports precedence (priority) for operators
- Operators with higher precedence are evaluated before operators with lower precedence
- Full List: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
- Multiplication (15) has higher precedence than addition (14) - multiplication wins
- Parentheses have the highest precedence (21) and always win:
(2 + 2) * 2 // 8
2 + (2 * 2) // 6
- When in doubt, use parentheses!
- What does the following return?
false && false || true
- Hint: Logical AND (6) has higher precedence than Logical OR (5)
(false && false) || true // false && false is false
false || true // returns true
Which of the two is more readable?
42 > 22 && 42 > 35
let myAge = 42;
let leftPersonAge = 22;
let rightPersonAge = 35;
let olderThanLeft = myAge > leftPersonAge;
let olderThanRight = myAge > rightPersonAge;
let isOldest = olderThanLeft && olderThanRight;
Group | Operators | Example |
---|---|---|
Numerical Operators | + - * / |
5 + 4 * 3 7 / 2 - 2 "Hello" + " World" |
Comparison Operators | === !== < > <= >= |
temperature !== 25 age >= 18 |
Logical Operators | || && ! |
a && !b x >= 5 && x < 15 |
Combined Operators | += -= *= /= ++ |
a *= 2 count++ |
let myAge = 42;
myAge = myAge + 1; // how old will I be next year?
Is the same as:
let myAge = 42;
myAge += 1; // same as myAge = myAge + 1
let price = 10;
// there's a 50 percent sale!
price /= 2;
Result: 5
- Operator
++
and--
increase (or decrease) the value of a variable by 1
let myAge = 42;
myAge++; // same as myAge = myAge + 1
6 % 3 // 0
7 % 3 // 1
8 % 3 // 2
9 % 3 // 0
10 % 3 // 1
11 % 3 // 2
12 % 3 // 0
- It shows you what integer remains when you divide one number by another
- Question: What is left when you divide 6 coins between 3 friends? Answer: 0 coins
- Question: What is left when you divide 8 coins between 3 friends? Answer: 2 coins
-
Variables are pointers to values:
- We can use operators with variables just like with values!
-
Use
<script>
to add a JavaScript file to your HTML webpage. -
Use
//
to write comments. -
Use
console.log(...)
to output stuff to the console.
You have an online shop, which sells hats and t-shirts. One of the customers wants to buy 2 hats and 3 t-shirts.
A hat costs 3.99€ and a t-shirt costs 9.99€. What is the total cost?
Create all the variables needed, and output the final result to the console.