Week 5 Flashcards
What are the datatypes in JavaScript?
Number, bigInt (values larger than -253 or 253), boolean, string, undefined, null, array (stores list of variables under a single variable), and object
What is Javascript?
Javascript is the most commonly used client-side language. It is a high-level, multi-paradigm, interpreted programming language used to create dynamic webpages. The browser interprets Javascript code in it and executes it.
Can JavaScript code be run on servers as the backend program for an application?
Although JavaScript originated as a scripting language that runs in the browser, the Node.js runtime environment does allow JavaScript code to be run on servers as the backend program for an application.
What does it mean to say JavaScript is a high level language?
It abstracts away many implementation details that relate to computer hardware - like allocating memory or garbage collection of objects.
What does it mean to say JavaScript is multi-paradigm?
It supports many programming paradigms like procedural, object-oriented, and functional programming.
What is the official name for JavaScript?
ECMAScript
In HTML, where is JavaScript code written?
In HTML, JavaScript code is written inside the and tags. You can place any number of scripts in an HTML document. Scripts can be placed in the , or in the section of an HTML page, or in both.
What is “internal JavaScript”?
When the JavaScript is code placed anywhere within the HTML page using tags
What is “external JavaScript”?
When JavaScript code is placed in a separate file from the HTML code. These files are saved with the “. js” extension and imported into the HTML page using the src attribute. The src attribute specifies the URL/path of an external JavaScript file. (Eg: )
Is JavaScript case sensitive?
Yes
How are statements separated in JavaScript?
Every statement in JavaScript is separated using a semicolon (;). JavaScript ignores multiple spaces and tabs.
What are JavaScript Literals?
Literals are the fixed values, they can be numbers, strings, boolean values, etc. The number type stores integer, float, and hexadecimal value. Strings are text, enclosed within single or double quotes (‘ or “). If numbers, characters, or words are enclosed with single or double quotes, then they are considered strings.
What are JavaScript keywords?
Keywords are tokens that have special meaning in JavaScript. The keywords supported by JavaScript are break, case, catch, continue, do, else, finally, for, function, if, in, new, return, switch, this, throw, try, typeof, var, void, while, etc.
What are JavaScript variables and how are they declared?
Variables are used to store data values. It uses the var keyword to declare variables. An equal sign (=) is used to assign values to variables. Variable names are identifiers that should not be a JavaScript keyword. They start only with the alphabet, underscores (_) or dollar ($). They cannot start with a number and also there shouldn’t be spaces in-between.
What are the Arithmetic Operators in JavaScript and what do they mean?
\+ addition - subtraction * multiplication / division % calculates remainder in a quotient \++ increment -- decrement
What are the Comparison Operators and what do they mean?
== “equals” - checks value NOT variable type - returns true or false boolean
=== “equals” - checks value AND variable type - returns true or false boolean
!= “not equal”
> greater than
< less than
>= greater than or equal to
<= less than or equal to
What are the Logical Operators and what do they mean?
&& and
|| or
! not
What are the Assignment Operators and what do they mean?
= is equal to \+= increment and is equal to -= decrement and is equal to *= multiply and is equal to /= divide and is equal to %= divides and assigns remainder to the variable
What is the Ternary Operator and what does it mean?
< condition > ? < value1 > : < value2 >;
Javascript operator that takes 3 operands. First a condition followed by a ?, then an expression to execute if the condition is true followed by a :, and finally an expression to execute if the condition is false. Frequently used as an alternative to an if…else statement
Ex. function getFee(isMember) { return (isMember ? '$2.00' : '$10.00'); }
console.log(getFee(true)); // expected output: "$2.00"
console.log(getFee(false)); // expected output: "$10.00"
console.log(getFee(null)); // expected output: "$10.00"
What are the Control Flow statements in JavaScript?
if/else for for-in for-of while do-while
What is the difference between for-in and for-of in JavaScript?
for-in allows iteration over the keys of an object
for-of allows iteration over an array or array-like object
Ex. let person = { name: 'Bob', age: 25 };
for (let prop in person) {
console.log(person[prop]); // prints ‘Bob’ and then 25
}
let people = [ { name: 'Alice', age: 30 }, { name: 'Charlie', age: 29 } ]
for (let pers of people) {
console.log(pers.name); // prints ‘Alice’ then ‘Charlie’
}
What are the advantages and disadvantages of JavaScript as compared to other programming languages?
Advantages
- Is a dynamically-typed language. JavaScript does not declare types before declaring or assigning a variable. Variables can hold the value of any data type at any point in time.
- JavaScript can run on a server or on a browser. Java and C# would have to be compiled to WebAssembly in order to run on modern-day browsers.
- JavaScript is a multi-paradigm language, meaning we can solve our problems in a variety of ways, functionally, object-oriented, or event-driven. With Java and C#, while many of those paradigms have support in the language, Object-oriented solutions are preferred. In JavaScript, functions are first-class variables, meaning that they are treated like any other variable and can be passed as arguments to other functions.
- JavaScript utilizes prototype-based objects. Java and C# utilize class-based objects. In ES6, JavaScript introduced class-based syntax which allows us to interface with our prototypes in a similar manner to Java and C#. However, OOP in JavaScript is accomplished very differently than in these other languages.
Disadvantages
- Due to being a dynamically-typed language, there is no static type checking available which could lead to issues with functions return a value of multiple types
- JavaScript is single-threaded and runs off of an event-loop. Java and C# support multi-threading.
- Due to using prototypes, an “overridden” method is merely shadowed on the prototype and is therefore still accessible.
- JavaScript has no concept of method/function overloading.
- Encapsulation is possible in JavaScript but there are no access modifiers and is not as simple as in other languages.
What is a function in JavaScript?
A group of reusable code which can be called anywhere in the program. All functions are passed by value meaning the value of any variable passed to a function is copied into the argument of the function. Any changes you make to the argument will not be reflected in the variable outside of the function.
What is an anonymous function in JavaScript?
An anonymous function is a function that is declared without any identifier to refer to it. It is an expression that the variable holds a function.
Ex.
var x = function (a, b) {return a * b};
Ex.
var anon = function() { alert('I am anonymous'); }; var prd = function (a, b) { return a * b;
};
anon();
alert(“prd = “ + prd(2,4));
What is a Self-Invoking Function (IIFE Function)?
A self-invoking function is an anonymous function that is invoked immediately after its definition. It is also known as the IIFE (Immediately Invoked Function Expression) function. It holds an anonymous function inside a set of parentheses (), which does the execution.
Ex.
(function(){ // do this right now console.log("Look at me, I'm running"); })();
What is a Callback Function and why are they useful?
A callback function is a function that gets executed after another function completes the execution.
It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors. JavaScript usually runs the code in sequential order (from top to bottom). If there is a case that code runs after some other execution, which is not happening in a sequence, this is called asynchronous programming.
All functions in JavaScript are objects and a JavaScript function can be passed another function as an argument.
Ex. function funcOne(x) { alert("x = " + x); }
function funcTwo(y, callback) { callback(y); }
funcTwo(2, funcOne);
What is a Closure?
A closure is a function that remembers and accesses the variables and arguments of its outer function even after the function return. The closure able to access the variables defined between its curly brackets, the outer function’s variables and the global variables.
Ex. function greeting() { var message = 'Hi';
function sayHi() { console.log(message); }
return sayHi; } let hi = greeting(); hi(); // prints "hi" in the console.
What is Hoisting?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. In JavaScript, variable declarations made with var and function declarations made with the function keyword are hoisted - or moved - to the top of the scope in which they are declared when the JavaScript interpreter parses the code. This means that variables and functions can be used before they are even declared.
Ex - Hoisting of Variables
//line 1 x = 1; document.getElementById("p1").innerHTML = x ; var x;
Ex - Hoisting of Functions
alert(Sum(5, 5)); // output: 10
function Sum(val1, val2) { return val1 + val2; }
Ex - Hoisting Functions Before Variables
alert(UseMe); // displays the UseMe Function definition
var UseMe = “UseMe Variable”;
function UseMe() { alert("UseMe function called"); }
What is the difference between “==” and “===” in JavaScript?
== is used for comparison between two variables irrespective of the data type of variable.
=== is used for comparison between two variables but this will check strict type, which means it will check datatype and compare two values.
What is Type Coercion in JavaScript? What are the different types of Type Coercion?
Type coercion is the process of converting a value from one data type to another data type.
Explicit type coercion - We can explicitly convert the datatype of the variable. For example: Number(‘3’), String (123), Boolean(2)
Implicit type coercion - JavaScript is a loosely-typed language, values can also be converted between different types automatically. It usually happens when you apply operators to values of different types. For example: ‘3’ * ‘2’, 2/’5’, 123 + ‘’
What is Falsy in JavaScript?
In JavaScript, any expressions or value that results in boolean false value, are considered as Falsy. The falsy values/expressions in javascript are:
Boolean false is false.
Any empty string will be evaluated to false.
Any undefined variable will be equal to false.
Any null variable will be equal to false.
Any numerical expression with result in NaN (not a number) will be equal to false.
Any numerical expression with result in zero will be equal to false.
What is Truthy in JavaScript?
In JavaScript, any expression or value that results in boolean true value, are considered as Truthy. Any expression or value that is not falsy is considered truthy.
What is Variable Scope?
The Variable scope defines the lifetime and visibility of a variable. Each variable is associated with a scope. The variable can be accessed only within its scope.
What is a Global Scope variable?
Variables defined outside any function, block, or module have global scope. The global scope variables are accessed everywhere in the application. The global variable’s lifetime is throughout the application. We can declare the global variables in a browser using the global window object.
What is a Function Scope Variable?
The variable declared in a function is only visible inside that function. var is the keyword to define variable for a function-scope accessibility. These variables cannot be accessed or modified.
What is a Block Scope Variable?
Block scope is the scope of the variables declared inside the {} (curly brackets). In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.
Ex. function func(){ if(true){ var fruit1 = 'apple'; //exist in function scope const fruit2 = 'banana'; //exist in block scope let fruit3 = 'strawberry'; //exist in block scope
} console.log(fruit1); console.log(fruit2); // results error - due to it exist in block scope console.log(fruit3); // results error - due to it exist in block scope }
foo();
Result
apple
error: fruit2 is not defined
error: fruit3 is not defined
What is a Lexical Scope variable?
Lexical scope means that a variable defined outside a function can access the inside of another function defined after the variable declaration. The inner functions are lexically bound to the execution context of their outer functions.
Ex function func1(){ var animal1 = "Lion"; //exist in Lexical scope
function func2(){ //Inner Function var animal2 = "Tiger"; //exist in function scope console. log(animal1); console. log(animal2); } func2(); console.log(animal2); // results error - due to it exist in function scope }
foo1();
Result
Lion
Tiger
error: animal2 is not defined
What is “Strict” mode?
JavaScript is a loosely typed scripting language. JavaScript allows strictness of code by using “use strict”; statement at the top of JavaScript code or in a function. The strict mode in JavaScript does not allow us to use undefined variables, reserved keywords as variable or function name, duplicate properties of an object, duplicate parameters of the function, assign values to read-only properties, Modifying arguments object, and Deleting an undeletable property. Strict mode can be applied to function level in order to implement strictness only in that particular function.
What is the “this” keyword and how does it behave in different contexts?
The this keyword is a reference variable that refers to the current object.
- this alone: refers to a global Object.
- this in a function: refers to the Global object [object Window].
- this in Event Handlers: refers to the HTML element that received the event
- this in Object Method Binding: refers to the object.
How can Encapsulation be achieved in JavaScript?
Encapsulation means hiding information or data. The simplest way to create encapsulation in JavaScript is using closures. A closure can be created as a function with private state. When creating many closures sharing the same private state, we create an object.
EX.
const Book = function(t, a) { let title = t; let author = a;
return { summary : function() { console.log(`${title} written by ${author}.`); } } } const book1 = new Book('Hippie', 'Paulo Coelho'); book1.summary(); // Returns Hippie written by Paulo Coelho.