Indicate in JavaScript what types of value are possible and which kind of operations.
3.141502653589793
"Hello world"
true
'This is a string' // single quotes are mostly used
"This is also a string" // double quotes can be used, but should be avoided
'What's up?' // This is an error
'What\s up?' // backslash to "escape" the quotes
"What's up?" //legit use of double quotes
"They said \"What's up?\"." // more quote escaping
'They said "What\'s up?".' // ... or use single quotes
console.log('Hello world');
Result: 'Hello world'
let x = 'This is a ';
x + 'string'; // add string to variable
Result: 'This is a string'
let y = 1;
x + y;
Result: 'This is a 1'
In variables you store data
//This is a comment. It won't get read by your browser.
//The next line declares a variable.
let x = 10;
var
defines a variable globally or locally to an
entire function.
var x;
let
defines a variable limited in scope to the
block, statement or expression in which it is used.
let x;
const
defines an
immutable variable in the same scope than
let.
const x;
You will need
let
, var
or
const
/* Multi-line comments are possible as well.
You can write any number you want. */
const pi = 3.141502653589793;
let name = 'Powercoders';
//This is called a string. It is in single or double quotes.
let bool = true;
//This is a Boolean.
var
?
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
var firstName = person.firstName;
var lastName = person.lastName;
var age = person.age;
var eyeColor = person.eyeColor;
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
let {lastName} = person;
const {firstName, age, eyeColor} = person;
In JavaScript each function creates a new scope.
Scope
determines the accessibility (visibility) of the declared variables.
Variables defined inside a function are not accessible (visible) from outside the function.
You are in the global scope, also called root scope by default if you are using JavaScript, the window object.
A global variable is short for a variable defined in global scope.
Variables declared outside of any functions are global.
A global variable can be used anywhere after its declaration.
Declare all global variables at the top of your JS file.
If you declare a variable inside a code block (e.g. function), you create a local scope, also called child scope or function scope
If you have variables inside your local scope, which are not declared there, it will check the global scope for the variable.
Scoping rules on variables were always very confusing and the reason for many bugs.
let
vs. var
var
is function-scoped. Every variable declared
inside the function is only accessible inside the function.let
is block-scoped (block is anything surrounded by
{}). Every variable declared inside a {} block is only accessible
inside that block. const
as well.
Best practice: use let
over var
. Use
const
for variables which do not change.
function q1() {
var a = 5;
if(a > 1) {
a = 3;
}
alert(a);
}
var b = 0;
function q2() {
b = 5;
}
function q22() {
alert(b);
}
function q3() {
window.a = "hello";
}
function q32() {
alert(a);
}
var b = 1;
function q4() {
var b = "test";
alert(b);
}
var c = 2;
if (true) {
var c = 5;
alert(c);
}
alert(c);
let c = 2;
if (true) {
let c = 5;
alert(c);
}
alert(c);
JavaScript is case sensitive.
// These are two different variables
let name = 'Powercoders';
let Name = 'Powercoders';
A variable can be declared without value.
let my_variable;
A variable declared without value is undefined.
The data type undefined
means the variable has not been
assigned.
prompt()
To get user input you can use prompt()
.
let name = prompt('What is your name?');
console.log('Hello ' + name);
Operator | Operation | Example | Result |
---|---|---|---|
+ |
Addition | 2 + 2 |
4 |
- |
Subtraction | 2 - 2 |
0 |
/ |
Division | 3 / 2 |
1.5 |
* |
Multiplication | 5 * 2 |
10 |
% |
Remainder / modulus | 9 % 2 |
1 |
8 % 2 |
0 |
||
** |
Exponention (xy) | 2**3 |
8 |
to add or substract 1 from a number.
Operator | Example | Result |
---|---|---|
val++ |
let a=0, b=10;
|
a=10 / b=11 |
++val |
let a=0, b=10;
|
a=11 / b=11 |
val-- |
let a=0, b=10;
|
a=10 / b=9 |
--val |
let a=0, b=10;
|
a=9 / b=9 |
Operator | Example | is equivalent to |
---|---|---|
= |
x = y |
x = y |
+= |
x += y |
x = x + y |
-= |
x -= y |
x = x - y |
*= |
x *= y |
x = x * y |
/= |
x /= y |
x = x / y |
%= |
x %= y |
x = x % y |
With conditions you can influence the code the browser will execute.
If the teacher is sitting in front of the laptop
she will go
to the next slide now.
if (statement) {
doSomething();
}
Only if the statement is true doSomething
will be
executed.
Booleans are used by JavaScript to check if a statement is true.
Logical operators allow you to connect as many expressions as you wish.
Operator | Description | Example |
---|---|---|
&& |
logical AND | true && true = true |
|| |
logical OR | true || false = true |
! |
logical NOT | !false = true |
True and False are often represented by 1 and 0.
A | B | A && B |
A || B |
! A |
|||
---|---|---|---|---|---|---|---|
0 | 0 | 0 | 0 | 1 | |||
0 | 1 | 0 | 1 | 1 | |||
1 | 0 | 0 | 1 | 0 | |||
1 | 1 | 1 | 1 | 0 |
Are used in logical statements to determine equility or difference between variables or values. They return true or false.
Operator | Description | let x=5; | Result |
---|---|---|---|
== | equal to | x == '5' | True |
=== | equal value and equal type | x === '5' | False |
!= | not equal | x != 3 | True |
> | greater than | x > 4 | True |
< | less than | x < 4 | False |
>= | greater than or equal to | x>=5 | True |
<= | less than or equal to | x<=4 | False |
if else
The else
statement tells JavaScript to execute
something if the condition is false.
if(statement){
doSomething();
} else {
doSomethingElse();
}
If the condition is false
doSomethingElse
will be executed.
condition ? expr1 : expr2
If the condition is true, provide expr1 else provide expr2.
It is like shorthand for an if
else
statement.
let age = 21;
let result;
if(age >= 20){
result = "User can view content";
} else {
result = "User cannot view content";
}
console.log(result);
let age = 21;
let result = age >= 20 ? "User can view content" : "User cannot view content";
console.log(result);
switch
In case of many different conditions resulting in different actions
use switch
instead of multiple
if/else if
statements.
switch(expression){
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
default
gets executed if no case matches.
Always have it.
break
will stop the execution of more code inside
the switch
block.switch
vs if else if
if else if
can test expressions based on conditions,
switch
only on a single integer or string
switch
is faster if there is a large group of values
to select among
if else if
is better for conditions resulting in true
or false
function moveCommand(direction) {
var whatHappens;
switch (direction) {
case "forward":
break;
whatHappens = "you encounter a monster";
case "back":
whatHappens = "you arrived home";
break;
break;
case "right":
return whatHappens = "you found a river";
case "left":
break;
return whatHappens = "you run into a troll";
break;
default:
whatHappens = "please enter a valid direction";
}
return whatHappens;
}
moveCommand("forward")
undefined
moveCommand("back")
you arrived home
moveCommand("right")
you found a river
So far our code has been linear, read line after line. Loops allow you to run the same code repeatedly, adding a different value each time.
There are several types of loops:
while
for
forEach
do while
for of
covered herefor in
covered herewhile
The while
loop is the easiest. It repeats through a
block of code, as long as a specified condition is
true.
while(statement){
//codeblock this gets looped until the statment is false
}
If a condition is always true, the loop will run
forever.
Make sure that the condition
eventually becomes false.
for
The for
loop is most commonly used. It has 3
statements, separated by semi-colons:
x=0
x<=5
x++
for(initialization; condition; iterator){
//codeblock this gets looped until the condition is false
}
do while
The do while
loop
will always be executed at least once, even if the
condition is false.
do { //code block here } while(statment);
The break
statement jumps out of a loop and continues
executing the code after the loop.
The return
keyword will also break the loop as it
immediately returns some value from a loop inside a function.
The continue
statement breaks
only one iteration in the loop and continues with
the next iteration.
A block of code designed to perform actions. The purpose is to perform a particular task (one piece of solving the problem).
window.alert()
window.prompt()
console.log()
function myFunction(param1, param2, param3){
return param1 + param2 * param3;
}
function
keyword to tell JS that a function
declaration starts.name
of the function
the same rules apply as in naming variables.
(param1, param2, param3)
directly after the
name for (optional) arguments.
The "placeholders" are called parameters.
You can have as many as you wish.
{}
holds the code to be executed when the function
is called.return
keyword (optional) breaks the execution and
returns the value.param1 + param2 * param3
is called the
return value.
You can only have one return value.
To execute the code inside a function, you need to call it.
let arg1 = 1;
let arg2 = 2;
let arg3 = 3;
myFunction(arg1, arg2, arg3);
name
- start by writing the name of the function(arguments)
- add the arguments in parentheses;
- always remember to use a semicolonWhen calling a function, provide the arguments in the same order in which you defined them.
Once the function is declared, you can call it everywhere as many times as you want:
You can give default arguments when declaring a function.
let myFunction = function(arg1=5, arg2=3, arg3=1){
return arg1 + arg2 * arg3;
}
myFunction();
myFunction(20);
We said that we can declare a function like this:
function myFunction(arg1, arg2, arg3) {
return arg1 + arg2 * arg3;
}
But a function can also be defined using an expression:
const myFunction = function(arg1, arg2, arg3) {
return arg1 + arg2 * arg3;
}
const
.
Function expressions become sometimes more useful than function declarations, e.g. if they are used as arguments to other functions.
(parameters) => {statements}
function (a){
return a + 100;
}
/**
* 1. Remove the word "function" and place arrow between
* the argument and opening body bracket */
(a) => {
return a + 100;
}
/**
* 1. Remove the word "function" and place arrow between
* the argument and opening body bracket */
(a) => {
return a + 100;
}
/**
* 2. Remove the body brackets and word "return" -- the return is implied.
*/
(a) => a + 100;
/**
* 2. Remove the body brackets and word "return" -- the return is implied.
*/
(a) => a + 100;
/**
* 3. Remove the argument parentheses
*/
a => a + 100;
() => { statements }
parameter => { statements }
parameter => expression
() => {
let x = 5 + 100;
alert(x);
}
a => {
let x = a + 100;
alert(x);
}
(a, b) => {
let x = a + b;
alert(x);
}
(a, b) => a + b;
A recursive function calls itself inside its code block.
let countdown = function(value) {
if (value > 0) {
console.log(value);
return countdown(value - 1);
} else {
return value;
}
};
countdown(10);
Arrays store multiple values in a single variable.
let topics = ["HTML","CSS","JS"];
You access an array element by referring to the index number written in square brackets.
let firstTopic = topics[0];
topics[2] = "jQuery";
// Possible to overwrite a value in an array
There are several ways how to declare an array
let topics = new Array(3);
topics[0] = "HTML";
topics[1] = "CSS";
topics[2] = "JS";
let topics = new Array(); // more dynamic without argument
topics[0] = "HTML";
topics[1] = "CSS";
topics[2] = "JS";
topics[3] = "PHP";
let topics = ["HTML","CSS","JS"] // recommended way to declare arrays
length
length
is a built-in JS property of any
object.length
returns the number of items inside an
array.length
is always one more than the
highest index.length
property returns
0.
In Javascript a multidimensional array is an array where each element is also an array.
let timeSpent = [
['Work', 9],
['Eat', 2],
['Commute', 1],
['Watch TV', 2],
['Sleep', 7]
];
console.log(timeSpent[0][1]);
To access an element of the multidimensional array, you first use
square brackets to access an element of the outer array which
returns an inner array; and then use another square bracket to
access the element of the inner array.
for...of
The for...of
loop is intended for iterating over
arrays, providing a simpler alternative to forEach
.
let list = ["doors", "windows", "rooms"];
for (let item of list) {
console.log(item);
}
It also works for all iterable objects, including strings:
for (let char of "hello") {
console.log(char);
}
forEach
The forEach
method, introduced in ES5, is easier to
read than the for
loop and prevents accidental breaking
of the loop.
list.forEach(function(value, index) {
// Code block here
console.log(value, index);
});
However, if you need to return
a value and break the
loop, forEach
is not suitable.
forEach
with arrow Functions (ES6)
In ES6, you can use arrow functions with forEach
for a
more concise syntax:
list.forEach((element, index) => {
// More code here
console.log(`Rank ${index + 1}: competitor: ${element}`);
});
concat
The concat
method merges two arrays into
one new array:
const t1 = ["HTML", "CSS"];
const t2 = ["JS", "PHP"];
const topics = t1.concat(t2);
console.log(topics); // ["HTML", "CSS", "JS", "PHP"]
Next to concat
these are some of the most important
methods you can use:
topics.toString()
This will return all the elements
as a string seperated by a comma.topics.push("MySQL")
This will add "MySQL" at the
end of the array.topics.pop()
This will return the last element of
the array and will remove it.topics.shift()
This will return the first element of
the array and will remove it.topics.sort()
This will sort the array
alphabetically.
array.filter()
//the old way
function WhoIsMe(){
let names = ["Susanne","Christina","Linus","Hany"];
for(let name of names){
if(name==="Susanne")
return "Susanne";
}
}
//the new way
let me = names.filter(name => {
return name==="Susanne";
});
array.map()
//the old way
let users = [{
name: "Susanne",
surname: 'Koenig',
age: 88
},{
name: "Andrina",
surname: 'Beuggert',
age: 88
}];
let allSurnames = [];
for(let user of users){
allSurnames.push(user.surname);
}
//the new way
let allSurnames = users.map(user => user.surname)
array.reduce()
//the old way
let cart = [
{
product_id: 89898,
product_name: 'Napkin red',
product_price: 6.50,
quantity: 10
},
{
product_id: 123,
product_name: 'Plastic forks',
product_price: 1.25,
quantity: 15
}
];
let total = 0;
for(let item of cart){
total += item.product_price * item.quantity;
}
//the new way
let total = cart.reduce((acc, current) =>
acc += current.product_price * current.quantity,0
);
An Object can contain many values and help organize and structure them.
An Object is a data type (like numbers or strings), but also a data structure.
An Object is a collection of data types. They can even have methods (=functions) in them.
Think of a collection as a list of values that are written as key:value pairs.
const person = {
name: "John",
age: 38,
eyeColor: "green",
isMarried: false
};
Javascript objects are containers for named values.
There are 2 ways to access an object property:
person.age;
person["age"];
This is how to access an object method:
person.hello();
// if you type person.hello without () you get back the defintion
console.log(person.name.length);
The log() function is actually a method of the console object.
The built-in length property is used to count the number of characters.
null
You can empty an object by setting it to null.
person = null;
person.name = "Susanne"; // not possible
const person = {
name: "John",
age: 38,
isMarried: false
};
Initializing the object this way, created
one single object.
But Simon and Marc are
persons, too.
We need a more general object type that can be used to create a number of objects of the same type.
function Person(name, age, married) {
this.name = name;
this.age = age;
this.isMarried = married;
this.sayHello = function() {
return "Hello " + this.name;
};
};
An object constructor is a function that performs the task of defining an object.
The this
keyword refers to the
current object.
You also need this
to access the variables of your own
object, e.g. inside a method.
Once you have an object constructor, use the
new
keyword to create a new object of the same type
called instance.
const susanne = new Person("Susanne", 41, false);
const max = new Person("Max", 25, true);
console.log(susanne.age); // Output: 41
console.log(max.sayHello()); // Output: Hello Max
susanne.age = 45; // Possible to change a property value
console.log(susanne.age); // Output: 45
susanne.gender = "female"; // Possible to add new property
console.log(susanne.gender); // Output: female
delete susanne.gender; // Possible to delete property
class Person {
constructor(name, age, married) {
this.name = name;
this.age = age;
this.isMarried = married;
}
hello() {
return "Hello " + this.name;
}
}
Object
object
Object.keys()
lists all property names of an object in
an array.
Object.values()
returns all property values of an
object in an array.
Object.keys(susanne);
// ["name", "age", "isMarried", "hello"]
The for in
loop is intended for iterating over the keys
of an object.
let obj = {doors: 2, windows: 8, rooms: 5};
for(let x in obj){
console.log(x);
}
x
is always a string.
Alternatively you can use Object.keys().forEach()
or
Object.values().forEach
to loop through an object.
let obj = {doors: 2, windows: 8, rooms: 5};
Object.keys(obj).forEach(function(property_name){
console.log(obj[property_name]);
});
let obj = {doors: 2, windows: 8, rooms: 5};
Object.values(obj).forEach(function(property_value){
console.log(property_value);
});
Math
to perform mathematical tasksDate
to work with datesMath
let pi = Math.PI;
console.log(Math.floor(pi));
console.log(Math.round(pi));
console.log(Math.ceil(pi));
let randomNumber = Math.ceil(Math.random() * 10);
console.log(randomNumber);
Date
function printTime(){
let currentDate = new Date();
let hours = currentDate.getHours();
let mins = currentDate.getMinutes();
let secs = currentDate.getSeconds();
console.log(hours + ":" + mins + ":" + secs +"\n");
}
setInterval(printTime, 1000); // prints current time each second
With []
in your property name, you can put in dynamic
values, like another variable or a calculation.
const name = "first name";
const obj = {
[name]: "Susanne",
[5 + 13]: 38,
experience: 13
}
Check what we learned so far on w3schools.com and mdn.com, e.g.
Dev Tools include a REPL (read, evaluate, print, loop), better known as console.
console.log('Hello ' + 'world');
Result: 'Hello world'
let x = 'This is a ';
x + 'string'; // add string to variable
Result: 'This is a string'
let y = 1;
x + y;
Result: 'This is a 1'
clear()
: clears the consolealert()
: writes output in a popupprompt()
: asks for input in a popupNumber()
: converts a string to a numberInheritance is a way to share common logic in programming
class Animal {
constructor(name) {
this.name = name;
}
jump() { console.log(`${this.name} is jumping.`); }
}
class Bird extends Animal {
fly() { console.log(`${this.name} is flying.`); }
}
class Dog extends Animal {
bark() { console.log(`${this.name} says "Woof!"`); }
}
const myDog = new Dog("Luna");
console.log(myDog.name); // "Luna"
myDog.jump(); // "Luna is jumping."
myDog.bark(); // "Luna says 'Woof!'"
myDog.fly(); // Uncaught TypeError: myDog.fly is not a function
However, we don't see jump or bark defined on the object:
jump()
)