Use Console tab for single line instruction. Executing single instruction at a time.
// Warning
alert('Hello');
// Confirm?
let val = confirm("Do you want to continue ?");
console.log('Confirm : '+ val);
let name = prompt("Enter your name:", "Enter your name here!");
console.log('Name : ' + name);
Use shift+Enter to add more line of instructions
alert('Hello'); // shift+Enter
alert('Dome Potikanond');
Instead, use the Source tab and the Snippet menu to create script (*.js) and use Ctrl+Enter to run the script.
JavaScript kewords: https://developer.mozilla.org/en-US/docs/Web/JavaScript
- String: "This is string", 'This is also a string'
- Numbers: 123
- Boolean: true, false
- Null: nothing (object)
- Undefined: no value (primitive)
In console, you can type these instructions
2+3;
alert(2+3);
typeof(23);
typeof('This is a string')
type(true);
Note: To clear the console, press Ctrl+L. There are 3 ways type of console output, i.e. log, error, and warning.
console.log('Hello World');
console.error('This is an error'); // red
console.warn('This is a warning'); // yellow
How can we remember value of data? There are 3 keywords relating to defining a variable.
- var : globally scope, due to hoisting (do not recommend)
- let : locally scope
- const : unless you need to reassign the value, try using this
There are primitive data types: String, Number, Boolean, null, undefined
const pi = Math.PI;
console.log(pi);
console.log(pi.toFixed(2));
let name = 'John Doe';
name = prompt('What is your name?');
console.log('Your name is '+ name);
// use back-tick `...` to quote with "template literals"
console.log(`Again, your name is ${name + '...'}`);
There are primitive data types: String, Number, Boolean, null, undefined
const name = 'John';
const height = 178;
const weight = 68.5; // also a number
const isCool = true;
const x = null; // empty value
const y = undefined
let z; // also undefined
console.log(typeof isCool);
console.log(typeof z);
The name can only contains letters, numbers, '$', and '_' (underscore). No other symbols are valid for naming.
Camel casing naming: first word are not capitalized!!! e.g. firstName, theFinalScore, ...
Note: To clear variables and cache, right-click on reload button and choose Empty cache and Hard reload or Ctrl+R.
Finding length of string using length property.
// Calculate available characters for tweet.
let max_length = 140;
let tweet = prompt("Enter your tweet:");
alert('You have written '+ tweet.length + ' characters, you have ' + (max_length-tweet.length) + ' characters left.' );
We can use slice method to get part of string.
let name = 'This is a good day to learn JS';
console.log( name.slice(0,4) );
console.log( name.slice(5,name.length) );
To cut your tweet input to only 30 characters.
let max_length = 40;
let tweet = prompt("Enter your tweet:");
alert('You have written '+ tweet.length + ' characters, you have ' + (max_length-tweet.length) + ' characters left.' + '\n\n' + tweet.slice(0,max_length) );
or
alert(prompt("Compose your tweet (max 40 characters):").slice(0,40));
Use .toUpperCase() and .toLowerCase() to change case of string.
// A script to get capitalized fist name
let name = prompt('What is your name?');
let firstChar = name.slice(0,1);
firstChar = firstChar.toUpperCase();
name = firstChar + name.slice(1,name.length).toLowerCase();
alert('Hello ' + name);
We can use the .split() method to split string into a list of list of multiple elements. Try this code.
let str1 = "Johny Trump";
console.log(str1.split());
console.log(str1.split(' '));
console.log(str1.split(''));
Traditional math operators (+,-,*,/,%) and precedences work the same way in JavaScript as in most computer languages.
let dogAge = prompt('enter dog age:');
let humanAge = (dogAge-2) * 4 + 21;
alert(dogAge + ' yrs old dog is equal to ' + humanAge + ' yrs old human.');
The increment/decrement, i.e. ++ and --, as well as those compounded assignments, i.e. += -= *= ..., also work the same way as in C++.
JavaScript is zero-based index array. To define an array, we can use assignement (=) or the new keyword.
// using constructor
const nums = new Array(1,2,3,4,5,6);
console.log(nums);
console.log(typeof(nums));
// using assignment
let arr = [1,2,3,4,5,6];
console.log(arr);
console.log(typeof(arr));
const fruits = ['apples', 'oranges', 'mango', 10, 14.5, true, [1,2,3]];
console.log(fruits);
fruits[6] = 'watermelon'; // add new item to the end of array
console.log(fruits);
fruits.push('end1'); // put an item to the end
fruits.unshift('start'); // put an item to the start
console.log(fruits);
fruits.pop(); fruits.pop() // pop 2 items out
console.log(fruits);
console.log("'hello' is array?: "+ Array.isArray('hello'))
console.log('fruit is array?: ' + Array.isArray(fruits));
console.log(fruits.indexOf('mango')); // find index of an item
Be careful when using assignment (=) because the new variable will share the same memory space due to the shallow copy.
let a1 = [1,2,3,4,5,6];
let a2 = a1;
a2[1] = '2222';
console.log(a2);
console.log(a1);
let a3 = a2.slice(0,3);
a3[2] = 333.333;
console.log(a3);
console.log(a2);
Array has some useful properties and methods.
let guestList = ['Angela','Jack','Pan','James','Lara','Jason'];
console.log(guestList.length);
console.log(guestList.includes('Dome'));
console.log(guestList.includes('Jack'));
It is possible to create object using the { ... }. Object contains key:value pairs of data.
const person = {
fname: 'Dome',
lname: 'Potikanond',
age: 42,
hobbies: ['music', 'movies', 'sports'],
address: {
street: '239 Huaykaew rd.',
city: 'Chiang Mai',
country: 'Thailand'
}
}
console.log(person);
console.log(person.fname + '(' + person.age + ')');
console.log(person.hobbies[1]);
console.log(person.address.street);
We can populate data inside an object to external variables using destructuring process.
// Destructuring - create variables from object properties
const { fname, lname } = person;
console.log(fname+' '+lname);
const { address: {city} } = person;
console.log(`${fname} ${lname} (${city})`);
To add new property, we use .key_name pattern.
// add new property
person.email = '[email protected]';
console.log(person);
We can create an array of objects as shown in the example below.
// Array of objects
const todos = [
{
id: 1,
text: 'Meeting with advisor',
isCompleted: true
},
{
id: 2,
text: 'Shopping for food',
isCompleted: false
},
{
id: 3,
text: 'Do web dev homework',
isCompleted: true
},
]
console.log(todos[1].text);
A format for data interchange between client/server. We can create JSON string out of JavaScript object using JSON.stringify() static method. To get back JavaScript object from JSON string, we use JSON.parse() static method.
const todoJSON = JSON.stringify(todos);
console.log(todoJSON);
let parseTodos = JSON.parse(todoJSON);
console.log(parseTodos)
Math.random() generate a random float between [0,1). To get random number between [1,6]
let n = Math.random();
console.log(Math.floor(n)*6+1);
prompt('What is your name?');
prompt('What is their name?');
let loveScore = Math.random() * 100;
loveScore = Math.floor(loveScore)+1
console.log('Your love score: ' + loveScore + '%')
if (loveScore === 100) {
console.log('You are true love!!!');
} else if (loveScore>=85) {
console.log('You are meant to be... definitely... quite sure!')
} else if (loveScore>=50 && loveScore<85) {
console.log('You are meant to be... probably!')
} else {
console.log('You may NOT be a good couple.');
}
- === : is equal to (with the same data type)
- == : is equal to (without checking data type)
- !== : is NOT equal to
- != : is NOT equal to
let a=1,b='1';
console.log(typeof(a));
console.log(typeof(b));
if (a === b)
console.log('yes, a === b');
if (a == b)
console.log('yes, a == b');
if (a !== b)
console.log('no, a !== b');
if (a != b)
console.log('no, a != b');
When a=1,b='1', the output of comparisons will be:
number
string
yes, a == b
no, a !== b
If we change a = 1, b = 1.0, the result will be:
number
number
yes, a === b
yes, a == b
If we change a = 1, b = '2', the result will be:
number
string
no, a !== b
no, a != b
JavaScript has for-loop and while-loop.
let i = 10;
let str = '';
while (i>0) {
str += `${i} `;
i--;
}
console.log(str);
for (let i=0; i<todos.length; i++) {
console.log(`${i+1}. ${todos[i].text}`);
}
There is another way of using for-loop with array.
// for each 'todo' in 'todos' array do something
for (let todo of todos) {
console.log(todo.id + ' - ' + todo.text);
}
JavaScript has a couple of useful array methods that take other function as argument.
- .forEach() : on each element apply function, does not create new array.
- .map() : create new array from input array.
- .filter() : create new array by filtering input array with speciied conditions.
// High-order loop: forEach, map, filter
todos.forEach( function(todo,index) { // forEach
console.log(`${index+1}: ${todo.text}`);
});
const todoText = todos.map( todo => { // Map
return todo.text;
});
console.log(todoText);
const todoCompleted = todos.filter( todo => { // Filter (and then Map)
return todo.isCompleted === true;
}).map( todo => {
return todo.text;
});
console.log(todoCompleted);
Packing series of instructions into a block of code and give it a name.
// function definition
function getMilk(bottles=1) {
console.log('go to the supermarket#1');
console.log('buy ' + bottles + ' bottle(s) of milk');
let cost = bottles * 1.5;
console.log('pay $'+ cost +', go back home');
console.log('put the milk in the refrigerator');
}
// calling the function
getMilk();
You can also use ES6 style arrow function to define your function.
getMilk2 = (bottles=1)=>{
console.log('go to the supermarket #2');
console.log('buy ' + bottles + ' bottle(s) of milk');
let cost = bottles * 1.5;
console.log('pay $'+ cost +', go back home');
console.log('put the milk in the refrigerator');
console.error('This is error msg');
}
getMilkByMoney = (money=0.0)=>{
console.log('go to the supermarket #2');
let numberOfBottles = Math.floor(money/1.5);
console.log('buy ' + numberOfBottles + ' bottle(s) of milk');
}
To get return value from function, we can use return keyword. The following function return the change money from buying milk.
function getMilkByMoney2(money=0.0, costPerBottle) {
console.log('go to the supermarket #2 with $' + money);
console.log('the milk cost $' + costPerBottle + '/bottle')
console.log('you can buy ' + calculateBottles(money, costPerBottle) + ' bottle(s) of milk');
return calculateChange(money, costPerBottle);
}
function calculateBottles(money=0.0, costPerBottle) {
let numberOfBottles = Math.floor(money/costPerBottle);
return numberOfBottles;
}
function calculateChange(money=0.0, costPerBottle) {
return money%costPerBottle;
}
console.log('You get $'+ getMilkByMoney2(20,3) + ' change.');
You will get the output as shown below:
go to the supermarket #2 with $20
the milk cost $3/bottle
you can buy 6 bottle(s) of milk
You get $2 change.
A couting program:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ...
Use .push() to add element to the end of a list and use .pop() to remove an item at the end of array.
let output = [];
let count = 1;
fizzBuzz = ()=> {
if (count%3 === 0 && count%5 === 0) {
output.push('FizzBuzz');
} else if (count%3 === 0) {
output.push('Fizz');
} else if (count%5 === 0) {
output.push('Buzz');
} else {
output.push(count);
}
count++;
console.log(output);
}
fizzBuzz();
fizzBuzz();
fizzBuzz();
fizzBuzz();
fizzBuzz();
fizzBuzz();
Now we can do Fizzbuzz process multiple times using while.
let output = [];
let count = 1;
while (count<40) {
if (count%3 === 0 && count%5 === 0) {
output.push('FizzBuzz');
} else if (count%3 === 0) {
output.push('Fizz');
} else if (count%5 === 0) {
output.push('Buzz');
} else {
output.push(count);
}
count++;
}
console.log(output);
We can also program Fizzbuzz using for as well. This time we count backward.
let output = [];
for (let count=50; count>0; count--) {
if (count%3 === 0 && count%5 === 0) {
output.push('FizzBuzz');
} else if (count%3 === 0) {
output.push('Fizz');
} else if (count%5 === 0) {
output.push('Buzz');
} else {
output.push(count);
}
}
console.log(output);
Let's create the fibonacci(n) function that return a list of fibonacci numbers up to the nth location.
function fibonacciGenerator (n) {
let output=[]
for (let i=0; i<n; i++) {
if (i===0)
output.push(0);
else if (i===1)
output.push(1);
else if (i>1)
output.push(output[i-1]+output[i-2]);
}
//Return an array of fibonacci numbers.
return output;
}