JavaScript Flashcards
Give an example of how to use a method to “find” an HTML element and change the element content?
document.getElementById(“demo”).innerHTML = “Hello JavaScript”;
What would be the code for having an image of a light bulb turn on and off with the fitting buttons?
Turn on the light
<img></img>
Turn off the light
In what sorts can JavaScript change HTML?
+ It can change the HTML content (e.g. with document.getElementById(“demo”).innerHTML = …”
+ It can change HTML Attribute Values (e.g. the src attribute of an <img></img> tag - lightbulb example)
+ It can change the HTML Styles (CSS) (e.g. document.getElementById(“demo”).style.fontSize = “35px”;
+ It can hide HTML elements (e.g. “document.getElementById(“demo”).style.display” = “none”)
+ It can show HTML elements (e.g. “document.getElementById(“demo”).style.display = “block”;
What is ECMA-262?
It’s the official name of the standard.
ECMAScript is the official name of the language.
ECMA is a standards organization for information and communication systems. It acquired its current name in 1994, when the European Computer Manufacturers Association (ECMA) changed its name to reflect the organization’s global reach and activities.
Where does the JavaScript code live in your HTML page?
It’s inserted between and .
You can place any number of scripts in an HTML document.
Scripts can be placed in the or in the >head> section of an HTML page, or in both.
What’s the benefit of placing scripts in the body instead of in the head?
It improves the display speed because script interpretation slows down the display.
How do you use external JavaScript files and what are their advantages?
The external files end with .js and are referred to in your HTML document as “ depending on its location or by referencing a full URL.
Advantages:
+ practical when same code is used in many different web pages
+ it seperates HTML and code
+ IT makes HTML and JavaScript easier to read and maintain
+ Cahced JavaScript files can speed up page loads
What are the different JavaScript display possibilities?
+ writing into an HTML element, using innerHTML
+ writing into the HTML output using document.write()
+ writing into an alert box, using window.alert() - here you can also leave out the “window” keyword.
+ writing into the browser console, using console.log()
What do you have to keep in mind with document.write()?
Using document.write() after an HTML document is loaded, will delete all existing HTML.
It should only be used for testing purposes.
What are JavaScript Programs?
A computer program is a list of “instructions” to be “executed” by a computer.
In a programing language, these programming instructions are called statements.
A JavaScript program (or JavaScript code) is a list of programming statements.
What are JavaScript statements composed of?
JavaScript statements are composed of \+ values \+ operators \+ expressions \+ keywords \+ comments
What are JavaScript Code Blocks and how are they indicated?
JavaScript statements can be grouped together in code blocks, inside curly brackets. They define statements to be executed together (e.g. in functions).
What does “break” do?
Terminates a switch or a loop.
What does “continue” do?
Jupos out of a loop and starts at the top.
What does “debugger” do?
Stops the execution of JavaScript and calls (if available) the debugging function.
What does “do…while” do?
Executes a block of statements and repeats the block while a condition is true.
What does “for” do?
Marks a block of statements to be executed, as long as a condition is true.
What does “function” do?
Declares a function.
What does “if…else” do?
Marks a block of statements to be executed, depending on a cndition.
What does “return” do?
Exits a function.
What does “try…catch” do?
Implements error handling to a block of statements.
What does “var” do?
Declares a variable.
What kind of JavaScript values do exist?
There are 2 types:
+ fixed values: Literals
+ variable values: Variables
What are the two most important syntax rules for fixed values?
- Numbers are written with or without decimals
2. Strings are text, written within double or single quotes
What is important to know about JavaScript variables?
Variables are used to store data values.
The keyword “var” is used to declare variables (without an “=”).
Use “=” to assign values to variables.
All variables must be identified with unique names which are called identifiers.
How do you write comments?
Code after // or between /* and */.
Is JavaScript case sensitive?
Yes. (e.g. JavaScript does not interpret VAR or Var as the keyword var)
What can you tell me about hyphens in JavaScript?
They are reserved for substractions and not allowed in names.
What are alternatives to “var” since 2015 and how are they used?
+ const = defines a variable that cannot be reassigned
+ let = defines a variable with restricted scope
How do you write the “equal to” operator in JavaScript?
”==”
“=” is an assignment operator
How do you declare a variable and assign a value to it?
var carName;
carName = “Volvo”;
or
var carName = “Volvo”;
You can declare many variables seperated by comma: var person = "John Doe", carName = "Volvo", price = 200;
Without assignment of a value to a variable, that variable will have the value “undefined”.
How are $ and _ treated in JavaScript?
They’re both treated as letters and can therefore be used as a start of a variable name (numbers are not allowed as the start of an identifier).
What is the Global Scope in JavaScript?
Variables declared globally (outside any function) have global scope and therefore can be accessed from anywhere in a JavaScript program.
What is the Function Scope in JavaScript?
Variables declared locally (inside a function) have Function Scope and can only be accessed from inside the function where they are declared.
What is a key difference between let and var when it comes to scope?
Varibales declared with the var keyword cannot have Block Scope. When they’re declared inside a block { } they can be accessed from outisde the block.
Varibales declared with the let keyword can have Block Scope and therefore cannot be accessed from outside the block.
Using “let” to redeclare a variable inside a block can be helpful.
Global variables defined with let cannot be used for the window command.
Why can a ReferenceError occur with let but not with var variables?
Varibales defined with var are hoisted to the top and can be initialized at any time - you can use the variable before it is declared.
Variables defined with let (and also with const) are hoisted to the top of the block but not initialized - so the block of code is aware of the variable, but it cannot be used until it has been declared.
What does the keyword const define?
It does not define a constant value - it defines a constant reference to a value.
You can change the properties of a constant object (e.g. change from red to white in the var color )- but you cannot reassign a constant object.
How can you also write
x = x+y
x=x-y
x=x*y
x+=y
x-=y
x*=y
The addition assignment operator (+=) adds a value to a variable.
How do you call the + operator when it’s used on strings?
Concatenation Operator
What does === mean?
equal value and equal type
What does ? as a comparison operator mean?
ternary operator
What is the difference between x**y and Math.pow(x,y) ?
there is non - they produce the same result
What is the return of
a) var x = 16 + 4 + “Volvo”?
b) var x = “Volvo” + 16 + 4
a) 20Volvo
b) Volvo164
How can you find out the type of a JavaScript variable?
ba using the typeof operator
What is the difference between
var car = undefined
and
var car = “”;
By setting a variable to undefined you’re emptying it and also setting its type to undefined.
An empty value has nothing to do with undefined. An empty string has both a legal vaule and a type.
Difference between undefined and null in types.
undefined and null are equal in value but different in type:
typeof undefined // undefined
typeof null // object
null === undefined //false
null == undefined // true
How many different types are there?
4 simple ones \+ string \+ number \+ boolean \+ undefined
2 complex ones:
+ function
+ object (for objects, arrays and null)
How is a function structured?
A function is structured with the function keyword, followed by a name, followed by parantheses () that may include paramter names separated by commas. Lastly the code to be executed by the function is place inside curly brackets {}
function name(para1, para2) { // code to be executed }
How do you assign values to variables outside vs inside of an object?
Outside of an object:
var car = “Fiat”;
Inside of an object:
var car = {type: "Fiat", model: "500", color: "white"]; --> those are name:values pairs and are called properties
What are object properties and how do you access them?
Object properties are name:values paris in an object and you access them either by
objectName.propertyName
or by objectName[“propertyName”]
What are object methods?
Objects can have methods - which are actions that can be performed on objects.
Methods are stored in porperties as function definitions.
- -> property: fullName
- -> property Value: function() { return this.firstName + “ “ + this.lastName;}
Name 6 common HTML events.
onchange = An HTML element has been changed onclick = The user clicks an HTML element onmouseover = The user moves the mouse over an HTML element onmouseout = The user moves the mouse away from an HTML emlement onkeydown = The user pushes a keyboard key onload = The browser has finished loading the page
What are common manipulations for strings?
stringName.length –> To find the length of a string
indexOf()
–> returns the index of (the position of) the first occurrence of a specified text in a string
–> lastIndexOf() returns the index of the last occurrence)
–> they both return -1 if the text is not found
–> they both accept a second parameter (e.g.
var str = “Please locate where ‘locate’ occurs!”);
var pos = str.indexOf(“locate”, 15);)
It indicates from what position it starts to search (from the back with lastIndexOf and from the start with indexOf)
search()
–> searches a string for a specified value and returns the position of the match
extracting string parts
- -> slice(start, end) - “end” is not included in new string; if a parameter is negative, the position is counted from the end of the string
- -> substring(start, end) - similar to slice but cannot accept negative indexes
- -> substr(start, length) - similar to slice but the 2nd parameter specifies the length of the extracted part; also can accept negative parameters in the 1st parameter
replace()
–> returns a new string concerning the first match it found; it’s case sensitive - to make it insensitive, use a regular expression with an /i flag (insensitive)
(e.g.
str = “please visit Microsoft!”;
var n = str.replace(/MICROSOFT/i, “W3Schools”);
to replace all matches, use a regular expression with a /g flag (global match)
toUpperCase();
toLowerCase();
concat()
–> joins two or more strings (same as using the plus operator)
trim()
–> removes whitespace from both sides of a string
charAt(position);
–> returns the character at a specified index (position) in a string;
charCodeAt(position);
–> returns the unicode of the character at a specified index in a string (so it returns a number)
padStart()
–> let str = “5”;
str = str.padStart(4,0); // result is 0005
padEnd()
split() --> convert a string into an array (e.g. var txt = "a,b,c,d,e"; txt.split(","); // Split on commas If the separator is omitted, the returned array will contain the whole string in index [0];
escape character –> using a backslash to turn special characters into string characters (e.g. " becomes “)
break code lines with a \ (e.g. “Hello \ Dolly!”;) but it’s not supported by all browsers, so the string addition is preferred to break up lines (e.g. “Hello” + “Dolly!”;
How can you turn a string into an object?
by adding the keyword new String to it (e.g. var firstName = new String(“John”);)
Downside: it slows down execution speed and complicates the code.
var x = 5; var y = 5;
y == x ?
Comparing two JavaScript objects will always return false.
How does JavaScript define numbers?
JavaScript does not define different types of numbers - they are always stored as double precision floating point numbers.
What is a specialty with the + operator in JavaScript?
It is used to add numbers and concatenate strings. (Adding a number to a string will result in a string concatenation)
Note: If you have any other operator than + this will work var x = "100" var y = "10" var z = x/y // z will be 10 as JavaScript will try to convert strings to numbers in all numeric operations (so dividing, minus, etc works, but + doesn't)
What does NaN stand for?
Not a Number
–> trying to do arithmetic with a non-numeric string will result in NaN
You can use isNaN() to find out if a value is a number.
NaN is a number: typeof NaN returns number
What are common number methods in JavaScript?
–> toString()
It returns a number as a string
–> toExponential()
It returns a string, with a number rounded and written using exponential notation.
e.g.:
varx = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4) // returns 9.6560e+0
(The parameter is optional - if you don’t specify it, JavaScript will not round the number)
–> toFixed()
It returns a string, with the number written with a specified number of decimals
(e.g. toFixed(2) is perfect for wworking iwth money)
--> toPrecision() It returns a string with a number written with a specified length (rounding it accordingly) e.g. var x = 9.656; x.toPrecision(); // returns 9.656 x.toPrecision(2) // returns 9.7
–> valueOf()
It returns a number as a number.
What are three JavaScript methods that can be used to convert variables to numbers?
number() / parseInt()
–> converts JavaScript variables to numbers
parseFloat()
–> It parses a string and returns a whole number. Spaces are allowed. Only the first number is returned.
–> they are global JavaScript methods
What is an array?
Arrays are used to store multiple values in a single variable.
The advantage is that it can hold many values under a single name and you can access the values by referring to an index number.
How do you create a new array?
var cars = [“Saab”, “Volvo”, “BMW”];
or
var cars = new Array(“Saab”, “Volvo”, “BMW”);
(the first method is preferred due to simplicity, readability and execution speed).
How do you access an array?
var name = cars[0];
var cars = ["Saab", "Volvo", "BMW"]; document.getelementById("demo").innerHTML = cars[0];
How do you change an array element?
cars[0] = “Opel”;
How can you access a full array?
It can be accessed by referring t the array name:
var cars [“saab”, “Volvo”, “BMW”]L
document.getelementbyID(Wdemo”).innerhTML = vars;
What are array properties?
–> length property returns the number of array elements are present. (The lenght is always one moe than the highest any rate)
How can you access the first and last array element?
1st: var first = fruits[0]
var last = fruits[fruits.length -1];
How do you loop through array elements?
With a for loop:
var fruits, text, fLen, i;
fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fLen = fruits.length;
text = "<ul>"; for (i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; } text += "</ul>";
Alternative:
using Array.forEach();
fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
text = “<ul>”;
fruits.forEach(myFunction);
text += “</ul>”;
function myFunction(value) { text += "<li>" + value + "</li>"; }
How do you add new elements to an array?
using the push() method:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Lemon"); // adds a new element (Lemon) to fruits
It can also be added using the length property:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
What is one of the differences between objects and arrays?
Arrays use numbered indexes, objects use named indexes.
You should use objects when you want the element names to be strings
ü you should use arrays when you want the element tnames to be numbers
How can you recognize an array?
The problem is that the JavaScript operator typeof returns “object because a JavaScript array is an object.
Sol.1:
use Array.isArray()
Sol.2:
you can create your own isArray(function)
What are common array methods?
toString()
Converts an array to a string of comma-separated array values.
join()
joins all array elements single string.
With this one you can also specify the separator
pop()
removes the last element from an array and returns the value that was popped out;
push()
adds a new element to an array at the end and returns the new array length as a value
shift()
removes the first array element and shifts all other elements to a lower index; it returns the string that was shifted out;
unshift()
adds a new element to an array at the beginning and unshifts older elements; it returns the new array length;
What are common methods to change, merge or delete in arrays?
Changing elements:
–> by saving a different value to an index
e.g.
var fruits = [“Banana”, “Orange, “Apple”];
fruits[0] = “Kiwi”;
–> by appending a new element to an array with the length property
e.g.
fruits[fruits.length] = “Kiwi”;
Deleting elements:
–> splicing an array
fruits.splice(2, 0, “Lemon”, “Kiwi”)
The 1st parameter (2) defines the position where new elements should be added (spliced in); the second parameter (0) defines how many elements should be removed. The splice() method returns an array with the deleted items.
–> slice()
slices out a piece of an array into a new array (it does not remove any elements from the source array but creates a new array with the sliced element);
it can take two parameters:
slice(1,3) // selects elements from the start argument and up to (but not including) the end argument; if only one parameter is used the method slices out the rest of the array.
Merging elements:
--> concat() creates a new array by merging existing arrays; e.g. var myGirls; var myBoys; var myChildren = myGirls.concat(myBoys);
How do you sort an array?
–> sort()
sorts an array alphabetically;
it will produce incorrect reesults when sorting numbers;
for numeric values rather use the compare function
–> function(a, b){return a-b}
This sorts the values according to the returned (negative, zero, positive) value in ascending order ({return b-a} will do it descending).
This is also a way how you can find the highest and lowest number as array[0] will hold the lowest value and array[array.length -1] will contain the highest value.
to sort object arrays you have to access the property you want to compare:
var cars = [
{type: “volvo”, year:2016},
{type: “Saab”, year: 2001}
];
cars.sort(function(a,b){return a.year - b.year});
--> sort in random order function(a, b){return 0.5 - Math.random()});
–> reverse()
reverses the elements in an array (you can use it to sort in descending order by first sort() and then revers() it)
What is the Fisher Yates Method?
it’s the most popular correct method to randomly sort an array:
var points = [40, 100, 1, 5, 25, 10];
for (i = points.length -1; i > 0; i--) { j = Math.floor(Math.random() * i) k = points[i] points[i] = points[j] points[j] = k }
How can you find the highest and lowest number in an array?
highest: function myArrayMax(arr) { return Math.max(arr); }
lowest: function myArrayMin(arr) { return Math.min(arr); }
How do you sort an array with string properties?
var cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ];
cars.sort(function(a, b){ var x = a.type.toLowerCase(); var y = b.type.toLowerCase(); if (x < y) {return -1;} if (x > y) {return 1;} return 0; });
What are commen array iteration methods?
Array.forEch() calls a function once for each array element and takes 3 arguments: \+ item value \+ item index \+ array itself
e.g.
var txt = “”;
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value, index, array) { txt = txt + value + "<br>"; }
Array.map()
creates a new array by performing a function on each array element (it does not change the original array)
e.g. var numbers1 = [45, 4, 9, 16, 25]; var numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) { return value * 2; }
Array.filter()
creates a new array with array elements that passes a test;
e.g. var numbers = [45, 4, 9, 16, 25]; var over18 = numbers.filter(myFunction);
function myFunction(value, index, array) { return value > 18; }
Array.reduce()
runs a function on each array element to produce (reduce it to) a single value (it does not reduce the original array)
e.g. var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value, index, array) { return total + value; }
Array.every()
checks if all array values pass a test
e.g. var numbers = [45, 4, 9, 16, 25]; var allOver18 = numbers.every(myFunction);
function myFunction(value, index, array) { return value > 18; }
similar to this: some()
–> checks if some array values pass a test
Array.indexOf()
searches an array for an element value and turns its position
Array.lastIndexOf()
same but returns the position of the last occurrence of the specified element
Array.find()
returns the value of the first array element that passes a test function
Array.findIndex()
returns the index of the first array element that passes a test function
What are the most common Math Methods?
The syntax is always the same:
Math.method.(number)
Math.round(x): Returns x rounded to its nearest integer
Math.ceil(x): Returns x rounded up to its nearest integer
Math.floor(x): Returns x rounded down to its nearest integer
Math.trunc(x): Returns the integer part of x (new in ES6)
What can you do with Math.random?
Math.random()
returns a random number between 0 and 1;
(–> it’s always lower than 1)
Math.random() combined with Math.floor() can be used to return random integers
e.g.
Math.floor(Math.random() * 10); // returns a random integer from 0 to 9
Math.floor(Math.random() * 10) + 1; // returns a random integer from 1 to 10
Booleans in JavaScript
Everything with a “value” is true.
e.g.
100, 3.14, -15, “Hello”
Everything without a "value" is false. e.g. var x = 0; Boolean(x); // returns false
False booleans: -0 "" (empty string) undefined null false NaN
Syntax of conditional statements (if, if else, else)
if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }
if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
How to use switch statements?
switch(expression) { case x: // code block break; case y: // code block break; default: // code block }
var x = "0"; switch (x) { case 0: text = "Off"; break; case 1: text = "On"; break; default: text = "No value found"; }
What different for loops do exist?
JavaScript supports different kinds of loops:
+ for - loops through a block of code a number of times
+ for/in - loops through the properties of an object
+ for/of - loops through the values of an iterable object
+ while - loops through a block of code while a specified condition is true
+ do/while - also loops through a block of code while a specified condition is true
The for loop
Syntax:
for (statement 1; statement 2; statement 3) { // code block to be executed }
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
for (i = 0; i < 5; i++) {
text += “The number is “ + i + “<br></br>”;
}
The For/In Loop
loops through the properties of an object or an array
Syntax: for (key in object) { // code block to be executed }
var person = {fname:”John”, lname:”Doe”, age:25};
var text = ""; var x; for (x in person) { text += person[x]; }
Do not use for in over an Array if the index order is important. Rather use a for loop, a for of loop or array.forEach() in that case.
The For/Of Loop
loops through the values of an iterable object
Syntax: for (variable of iterable) { // code block to be executed }
let cars = [“BMW”, “Volvo”, “Mini”];
let text = “”;
for (let x of cars) {
text += x + “<br></br>”;
}
The While Loop
loops through a block of code as long as a specified condition is true.
Syntax: while (condition) { // code block to be executed }
while (i < 10) {
text += “The number is “ + i;
i++;
}
The Do/While Loop
is a variant of the while loop. It will execute the code block once before checking if the condition is true (because the code block is executed before the condition is tested) , then it will repeat the loop as long as the condition is true.
Syntax: do { // code block to be executed } while (condition);
do { text += "The number is " + i; i++; } while (i < 10);