Basic JavaScript Flashcards
What is JavaScript and what do we need it for?
JavaScript is a scripting or programming language that allows you to implement complex features on web pages. To better understand what JavaScript does, analyze it in the context how it talks with HTML and CSS:
- HTML is the markup language that we use to structure and give meaning to our web content, for example defining paragraphs, headings, and data tables, or embedding images and videos in the page.
- CSS is a language of style rules that we use to apply styling to our HTML content, for example setting background colors and fonts, and laying out our content in multiple columns.
- JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else.
Difference between Compiled and Interpreted language?
Code compilation is a set of steps that process the text of your code and turn it into a list of instructions the computer can understand. Typically, the whole source code is transformed at once, and those resulting instructions are saved as output (usually in a file) that can later be executed.
Interpretation performs a similar task to compilation, in that it transforms your program into machine-understandable instructions. But the processing model is fairly different. Unlike a program being compiled all at once, with interpretation the source code is typically transformed line-by-line.
4 ways of displaying data with JavaScript
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Ways of commenting code
// Single line comments
/*Multi line Comment */
CTRL+ /
What is a variable?
In programming, just like in algebra, we use variables (like price1) to hold values.
In programming, just like in algebra, we use variables in expressions (total = price1 + price2).
All JavaScript variables need to be identified with unique names (identifiers)
The attributes of a variable are:
- name
- identifier (identifies place in memory)
- value
- we can also add one more attribute - lifetime of a function, which is dependent on the scope.
What are falsy values?
The falsy values in JavaScript are 0, 0n, null, undefined, false, NaN, and the empty string “”. They evaluate to false when coerced by JavaScript’s typing engine into a boolean value, but they are not necessarily equal to each other.
To the contrary, the values below are truthy:
“string”, 42, [], {}, function foo() {}
Operands and operators
Mathematically, anoperationis a calculation on one or more values calledoperandsmapping to an output value. An operator is a symbol/sign that maps operands to output values.
x + y = z
In the equation above x and y are operands, + and = are operators while z is the result
What are unary operators?
A unary operation is an operation with only one operand. Unary operators are more efficient than standard JavaScript function calls. Additionally, unary operators can not be overridden, therefore their functionality is guaranteed.
What are the types of unary operators?
Unary plus (+) Tries to convert the operand into a number* Unary negation (-) *Tries to convert the operand into a number and negates after Logical Not (!) Converts to boolean value then negates it Increment (++) Adds one to its operand Decrement (--) Decrements by one from its operand Bitwise not (~) Inverts all the bits in the operand and returns a number typeof Returns a string which is the type of the operand delete Deletes specific index of an array or specific property of an object void Discards a return value of an expression.
How to create a valid variable name.
To create a variable name you need to:
Start with One of: _ $ letter
Followed by Zero or More: _ $ letter number
Variables that begin with _ usually denote that this variable will be private in some way
Variables starting with $ are usually for automatically generated code.
__proto__ variables reserved for non-standard features
What is the main difference between var and let keywords?
Main difference is scoping rules
to be continued..
Hoisting
let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a ReferenceError. Variable said to be in “temporal dead zone” from the start of the block until the initialization is processed.
Redeclaration
In strict mode, var will let you re-declare the same variable in the same scope while let raises a SyntaxError.
Leakage
When you declare let variables inside of a code block, it is declared just inside this code block, while doing it with var keyword would leak the variable when called outside of the block. var variables DO NOT have block scope.
What are types of values in JS
Primitives: Boolean, Null, Undefined, Number, String
Technically - also Symbol and BigInt
1 complex: Object
How we can interpolate variable into a string?
You can put strings in “”,
‘’,
or backticks ``
By using backticks you can embed js code into a string like Hello, ${userName}
What value do you set the variable to, if you want to wipe out the value?
It is best practice to set the variable to null.
Undefined means that we have not initialized a variable in script, while null will show that the programmer set the value himself
What you should keep in mind when compare results of calculations to a literal (especially in an if clause)?
That JavaScript uses inaccurate floating point numbers.
When you make calculations, try to bear in mind that you need to use toFixed() function
However toFixed() method converts to a string, to convert to a number you need to use ‘+’ sign before the expression.
as in example:
if ( +(1.1 + 1.3).toFixed(2) == 2.4){
showMessage(‘true’);
}
What is the role of ternary operator?
Ternary operator is essentially a short-cut to if statements. They also allow us to input a value to a variable, where standard if /else statement couldn’t do it
// (condition) ? true-stement : false-statement;
let message = ( price > 10 ) ? ‘expensive’ : ‘cheap’
showMessage(message); //expensive
What is the role of symbol?
Symbols can be used inside of an object to hide information.
What is the difference between slice and splice methods?
Both methods are allowing us to manipulate arrays.
splice() changes the original array whereas slice() doesn’t but both of them returns array object. Splice also allows us to replace values that were deleted.
slice(0,4) - will return an array starting from index 0, but index 4 will not be included [0, 1, 2, 3];
splice(1,2) - will return an array starting from index 1 and will be two element
splice(3,1, ‘hamster’) - will replace the element at 3rd index with ‘hamster’
What are rest parameters?
Rest parameter- Collects all remaining arguments into an actual array.
function sumAll(...nums) { let total = 0; for (let n of nums) total+=n; return total }
What is destructuring and how can it be applied
Destructuring is a short, clean syntax to ‘unpack’:
- values from arrays
- properties from objects
Into distinct variables.
const [gold, silver, bronze] = raceResults;
const {first,last} = runner;
What is spread?
Spread syntax allows us to take an array and spread its elements so they can be assigned to parameters.
Spread has many usecases:
1) Spread for Function Calls (Expands and iterable into a list of arguments)
const nums = [9,3,2,8]
Math.max(…nums) //same as calling Math.max(9,3,2,8)
2) Spread in Array Literals (Create a new aray using an existing array. Spreads the elements from one array into a new array)
[…nums1, …nums2, 7, 8, 9] // Can also be used to make a copy of an array
3) Spread in object literals (Copies properties from one object into another object literal)
What does continue keyword do to a loop?
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
As in example: for (let i=0; i<5; i++) { if (i===3) continue; console.log(i); } 0 1 2 4 will be printed
What are IIFE’s?
Immediately Invoked Function Expression.
By Immediately invoked we mean that it is ran immediately after it’s declared.
You can close the function in parenteses and then immediately invoke it:
(function() {
console.log(“Example”);
})();
What are the differences between call an apply functions
call and apply are both used to change the value of this. within a function.
With call and apply functions we are allowed to pass an object to a function.
let welcome = function(){
console.log(‘Hello “ + this.name);
}
welcome.call(person1) // Hello John
Thedifference between call and apply is that call requires the arguments to be passed in one-by-one, and apply takes the arguments as an array.
Use apply() when the input parameter is already in the form of array with similar elements
Use call if you are dealing with multiple arguments that are not really related to each other
What bind function does?
While call and apply functions allow us to call a function and change the this. value.
We call bind. on a function and it makes a copy a function and assings a new context (a value that has been assigned by this.).
What are arrow functions and how do they behave?
ES6 arrow functions can’t be bound to a this keyword, so it will lexically go up a scope, and use the value of this in the scope in which it was defined.
The big change:
Arrow functions do not have their own “this” value.
“this” refers to the enclosing context. The value of this is always inherited from the enclosed scope.
Regular functions’ this value refers to the object that holds the function.
How do you add default parameters for a function?
function(carId, city= 'NY'){ }
Whenever the function is called with only carId argument, the default one for city will be ‘NY’.
Introduced in ES6.
What is a constructor?
A constructor is a function that gets executed when a new instance of an object is created.
For constructor function to work properly we need to declare new object with new keyword.
let vehicle = new Car();
because this. in constructor function function Car() { console.log(this); } is referred to the global scope if we simply call Car();
The most important thing to keep in mind when working with objects like this and constructor functions is to use this. keyword, to access the context of the object.
What are prototypes used for?
The problem with constructor object is that when we create 100.000 objects like this, the functions would be replicated 100.000 times.
That’s where prototypes come in.
User.prototype.usrCreated = function(){
console.log(“User “ + this.userName+’#’+this.userId +’ has been created!’);
};
When you use prototypes remember that you still need to reference to the object with this. keyword