Created by
function add(x,y){
return x+y
}
const add = function(x,y){
return x+y
};
const f = function add(x,y){
return x+y
};
console.log("f(2,3):", f(2,3)); // f(2,3):5
console.log("add(2,3):", add(2,3)); // ReferenceError: add is not defined
const sumLog = new Function('a', 'b', 'console.log(`a + b = ${a+b}`)');
sumLog(2,4);
the strict ES2015 behaviour
if (0){
function add(x,y){
x+y;
};
};
console.log("add:", add); // undefined
Safer way:
var add;
if (0){
// function expressions are not hoisted
add = function(x,y){
x+y;
};
};
console.log("add:", add); // undefined
let x = 1, y=1; // x and y in global scope
function foo(){
let x = 2, y=2; // x and y in foo scope
function bar(){
let y = 3; // y in bar scope
x = 3; // uses x in foo scope
console.log(`x,y in bar: ${x}, ${y}`);
}
bar();
console.log(`x,y in foo: ${x}, ${y}`);
}
foo();
console.log(`x,y in global: ${x}, ${y}`);
// OUTPUT:
//x,y in bar: 3, 3
//x,y in foo: 3, 2
//x,y in global: 1, 1
From its creation back in 1995, JavaScript supports function as first-class citizens (objects)
JavaScript's C-like syntax, including curly braces and the clunky for statement, makes it appear to be an ordinary procedural language. This is misleading because JavaScript has more in common with functional languages like Lisp or Scheme than with C or Java
return
operator.
function callback() {
console.log(`I will be called!`);
}
function caller( f ){
console.log(`This is the CALLER`);
f();
}
// we pass the callback function to caller
caller( callback );
// This is the CALLER
// I will be called!
const greeting = function(){
alert("Welcome");
}
// SetTimeout will call the greeting after 4s
setTimeout(greeting, 4000);
function as return value
const greeting = function(name){
return function(){
alert("Welcome, "+ name);
}
}
setTimeout(greeting("Ada"), 4000);
const sum = function(x){
return function(y){
return x+y;
}
}
console.log( "sum:", sum(2)(3) );
( function(){} )();
function(){}
is an anonymous function declaration!( function(){} )
is an anonymous function expression!
(function(x,y){
console.log( x+y );
})(2,3);
is the same as
(function(x,y){
console.log( x+y );
}(2,3));
{
// if you use only let and const to declare variables,
// your program will not export any global variables!
let x = 2;
let y = 3;
// other code
}
function outer(){
const x = 5;
function inner(){
console.log(x);
}
return inner;
}
const f = outer();
f(); // f can access the local x !
var cats = [];
for (var i = 0; i < 3; i++) {
cats[i] = function(){
console.log(`Cat ${i} is ready!`);
}
}
cats[0](); //Cat 3 is ready!
cats[1](); //Cat 3 is ready!
cats[2](); //Cat 3 is ready!
the value of 'i' in the cats[i] function body is determined when the function is invoked!
var cats = [];
for (var i = 0; i < 3; i++) {
(function(i){
cats[i] = function(){
console.log(`Cat ${i} is ready!`);
}
})(i)
}
cats[0](); //Cat 0 is ready!
cats[1](); //Cat 1 is ready!
cats[2](); //Cat 2 is ready!
The value of i - which is a parameter to the IIFE is preserved in cats[i]
functions, when they are called outside the IIFE scope.
var cats = [];
function catMaker(i){
return function(){
console.log(`Cat ${i} is ready!`);
}
}
for (var i = 0; i < 3; i++) {
cats[i] = catMaker(i);
}
cats[0](); //Cat 0 is ready!
cats[1](); //Cat 1 is ready!
cats[2](); //Cat 2 is ready!
Definitely, this is the simplest solution :)
var cats = [];
for (let i = 0; i < 3; i++) {
cats[i] = function(){
console.log(`Cat ${i} is ready!`);
}
}
cats[0](); //Cat 0 is ready!
cats[1](); //Cat 1 is ready!
cats[2](); //Cat 2 is ready!
var colors = ["red", "green", "blue"];
for (var i = 0; i < colors.length; i++) {
setTimeout(function(){
changeBG("box", colors[i]);
}, 1000)
}
function changeBG(id, color){
var node = document.getElementById(id);
node.style.background = color;
}
var colors = ["red", "green", "blue"];
for (var i = 0; i < colors.length; i++) {
(function(i){
setTimeout(function(){
changeBG("box", colors[i]);
}, 1000*i)
})(i);
}
function changeBG(id, color){
var node = document.getElementById(id);
node.style.background = color;
}
setTimeout() is invoked immediately 3 times. The delay is for the inner function. If we pass same delay, they will be invoked simultaneously after the delay. So, we need to change the delay, as well, i.e. i*1000
var colors = ["red", "green", "blue"];
for (var i = 0; i < colors.length; i++) {
doTimeout(i);
}
function doTimeout(i){
setTimeout(function(){
changeBG("box", colors[i]);
}, i*1000)
}
function changeBG(id, color){
var node = document.getElementById(id);
node.style.background = color;
}
n! = (n-1)!*n, if n > 0
n! = 1, if n = 0
Reference: Факториел @wikipedia
function factorial(n){
if(n===0){ // recursion end condition
return 1
}else{
return n*factorial(n-1) // recursive call
}
}
factorial(3);
function fact(n) {
return n===0? 1: n*factorial(n-1);
}
Write down a function which uses the iterative approach (i.e. - loop) to solve the Factorial problem
baseexp = base * baseexp - 1
base0 = 1
function power(base, exponent) {
if (exponent === 0)
return 1;
else
return base * power(base, exponent - 1);
}
console.log(power(2, 10));
// same with ternary operator
function power(base, exponent) {
return exponent === 0 ? 1 : base * power(base, exponent - 1);
}
console.log(power(2, 10));
Write down a function which uses the iterative approach (i.e. - loop) to solve the Power problem
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TASJ_DOM_Travers</title>
</head>
<body>
<p>TASK: apply backgroundColor:"red" for each elelement in #startNode, which has class "red"</p>
<p>paragraph 2</p>
<ul id="startNode">
<li>
<ol>
<li class="red">make me red</li>
<li>do not make me red</li>
</ol>
</li>
<li class="red">make me red</li>
</ul>
<ol>
<li class="red">do not make me red</li>
</ol>
<script>
function doSomething(node) {
if (node.classList.contains("red")) {
node.style.backgroundColor = "red";
console.log(node.className);
}
};
// HW: fix it
function traverseDOM(node) {
// get all HTML child nodes of node
let children = node.children;
// loop over children:
for (let i = 0; i < children.length; i++) {
let el = children[i];
// do something with each child element:
doSomething(el);
traverseDOM(el);
}
}
let startNode = document.querySelector("#startNode");
traverseDOM( startNode );
</script>
</body>
</html>
See the Pen traverseDOM_ElementNodes by Iva Popova (@webdesigncourse) on CodePen.
See the Pen traverseDOM_ElementNodes_Crockford by Iva Popova (@webdesigncourse) on CodePen.
See the Pen traverseDOM_AllNodes by Iva Popova (@webdesigncourse) on CodePen.
/* -------------------------------------------------------------------------- */
/* task: countEvenNumbers */
/* -------------------------------------------------------------------------- */
// Да се дефинира функция countEvenNumbers, която връща броя четни числа в
// подаденият й масив от числа:
function countEvenNumbers(arr) {
let evenCount = 0;
for (let i = 0; i < arr.length; i++) {
const number = arr[i];
if(number%2===0){
evenCount+=1;
}
}
return evenCount;
}
// примерно извикване:
let evenCount = countEvenNumbers( [1,4,2,3,5] );
console.log( evenCount );
// 2
/* -------------------------------------------------------------------------- */
/* task: generateRandomNumber */
/* -------------------------------------------------------------------------- */
// Да се дефинира функцията generateRandomNumber(start, end), която генерира
// цяло случайно число в интервала, зададен чрез параметрите start и end.
// Hint: използвайте Math.random() функцията за генериране на случайно число.
function generateRandomNumber(start,end) {
return Math.floor(Math.random() * (start - end + 1)) + end;
}
// примерно извикване:
let randomNumber = generateRandomNumber(1,100);
console.log( randomNumber );
// randomNumber трябва да е цяло число, 1 >= randomNumber <=100
/* -------------------------------------------------------------------------- */
/* task */
/* -------------------------------------------------------------------------- */
// Да се дефинира функция SumEven2DimArrayElements(), която връща сумата от
// четните елементи на подаден й двумерен масив.
let arr = [
[1,2,3],
[4,5,6]
];
function SumEven2DimArrayElements(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
const row = arr[i];
for (let j = 0; j < row.length; j++) {
const number = row[j];
if(number%2===0){
sum+=number;
}
}
}
return sum;
}
// Примерно извикване на функцията:
let sum = SumEven2DimArrayElements(arr);
console.log(sum);
// expected output: 12
/* -------------------------------------------------------------------------- */
/* task: isPalindrome */
/* -------------------------------------------------------------------------- */
// Да се дефинира функция isPalindrome, която връща "true" ако подадената й
// като аргумент дума е палиндром, и "false" - ако думата не е палиндром.
// Палиндром е дума, която се чете по един и същ начин от ляво надясно и от
// дясно наляво. Пример за палиндром са: мадам, боб, капак.
function isPalindrome(word) {
// изчисляваме индекса, който маркира средата на думата:
let middle = Math.floor(word.length/2);
// console.log(`middle index of ${word} is: ${middle}`);
for (let i = 0; i < middle; i++) {
let j = word.length - 1 - i;
if(word[i]!==word[j]){
// the word is not palindrome
return false
}
}
// the word is palindrome
return true;
}
// примерно извикване:
console.log( isPalindrome("madam") );// true
console.log( isPalindrome("test") ); // false
These slides are based on
customised version of
framework