Javascript_Level_6

Ace your homework & exams now with Quizwiz!

Singleton Design Pattern Implementation

/* Lazy Instantiation skeleton for a singleton pattern */ var MyNameSpace = {}; MyNameSpace.Singleton = (function() { // Private attribute that holds the single instance var singletonInstance; // All of the normal code goes here function constructor() { // Private members var privateVar1 = "Nishant"; var privateVar2 = [1,2,3,4,5]; function privateMethod1() { // code stuff } function privateMethod1() { // code stuff } return { attribute1 : "Nishant", publicMethod: function() { alert("Nishant");// some code logic } } } return { // public method (Global access point to Singleton object) getInstance: function() { //instance already exist then return if(!singletonInstance) { singletonInstance = constructor(); } return singletonInstance; } } })(); // getting access of publicMethod console.log(MyNamespace.Singleton.getInstance().publicMethod()); The singleton implemented above is easy to understand. The singleton class maintains a static reference to the lone singleton instance and return that reference from the static getInstance() method.

var k = 1; if (1) { function foo(){}; k += typeof foo; } console.log(k);

// output 1function

What would be the output of following code ? function funcA(){ console.log("funcA ", this); (function innerFuncA1(){ console.log("innerFunc1", this); (function innerFunA11(){ console.log("innerFunA11", this); })(); })(); } console.log(funcA()); funcA Window {...} innerFunc1 Window {...} innerFunA11 Window {...} undefined Type Error ReferenceError: this is not defined

1)

What would be the output of following code? (function () { var array = new Array('a', 'b', 'c', 'd', 'e'); array[10] = 'f'; delete array[10]; console.log(array.length); }()); 11 5 6 undefined

1) 11

What would the output of following code ? var obj = { message: "Hello", innerMessage: function() { console.log(this.message); } }; console.log(obj.innerMessage()); Hello undefined Type Error ReferenceError: this.message is not defined

1) Hello

What would the output of following code ? function Person(name, age){ this.name = name || "John"; this.age = age || 24; this.displayName = function(){ console.log(this.name); } } Person.name = "John"; Person.displayName = function(){ console.log(this.name); } var person1 = new Person('Nishant'); person1.displayName(); Person.displayName(); Nishant Person Nishant John Nishant undefined John John

1) Nishant Person

What would be the output of following code? (function() { var array1 = []; var array2 = new Array(100); var array3 = new Array(['1',2,'3',4,5.6]); console.log(array1); console.log(array2); console.log(array3); console.log(array3.length); }()); [] [] [Array[5]] 1 [] [undefined × 100] Array[5] 5 [] [] ['1',2,'3',4,5.6] 5 [] [] [Array[5]] 5

1) [] [] [Array[5]] 1

What would be the output of following code ? (function() { var objA = { foo: 'foo', bar: 'bar' }; var objB = { foo: 'foo', bar: 'bar' }; console.log(objA == objB); console.log(objA === objB); }()); false true false false true false true true

2) false false

What would be the output of following code? console.log(employeeId); var employeeId = '19000'; Some Value undefined Type Error ReferenceError: employeeId is not defined

2) undefined

What would be the output of following code? var employeeId = '1234abe'; (function(){ console.log(employeeId); var employeeId = '122345'; })(); '122345' undefined Type Error ReferenceError: employeeId is not defined

2) undefined

What would be the output of following code? (function(){ var animal = ['cow','horse']; animal.push('cat'); animal.push('dog','rat','goat'); console.log(animal.length); })(); 4 5 6 undefined

3) 6

What would be the output of following code? (function() { var array = new Array('100'); console.log(array); console.log(array.length); }()); undefined undefined [undefined × 100] 100 ["100"] 1 ReferenceError: array is not defined

3) ["100"] 1

Object 1. What would be the output of following code ? (function() { 'use strict'; var person = { name: 'Nishant' }; person.salary = '10000$'; person['country'] = 'USA'; Object.defineProperty(person, 'phoneNo', { value: '8888888888', enumerable: true }) console.log(Object.keys(person)); })(); Type Error undefined ["name", "salary", "country", "phoneNo"] ["name", "salary", "country"]

3) ["name", "salary", "country", "phoneNo"]

What would the output of following code ? var obj = { message: 'Hello', innerMessage: function () { (function () { console.log(this.message); }()); } }; console.log(obj.innerMessage()); Type Error Hello undefined ReferenceError: this.message is not defined

3) undefined

Hoisting 1. console.log(employeeId); Some Value Undefined Type Error ReferenceError: employeeId is not defined

4) ReferenceError: employeeId is not defined

What would be the output of following code ? (function() { 'use strict'; var person = { name: 'Nishant' }; person.salary = '10000$'; person['country'] = 'USA'; Object.defineProperty(person, 'phoneNo', { value: '8888888888', enumerable: false }) console.log(Object.keys(person)); })(); Type Error undefined ["name", "salary", "country", "phoneNo"] ["name", "salary", "country"]

4) ["name", "salary", "country"]

What would be the output of following code ? var obj = { message: "Hello", innerMessage: !(function() { console.log(this.message); })() }; console.log(obj.innerMessage); ReferenceError: this.message is not defined undefined Type Error undefined true

4) undefined true

What is a "closure" in JavaScript? Provide an example

A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in the parent function scope. The closure has access to variables in three scopes: Variables declared in their own scope Variables declared in a parent function scope Variables declared in the global namespace var globalVar = "abc"; // Parent self invoking function (function outerFunction (outerArg) { // begin of scope outerFunction // Variable declared in outerFunction function scope var outerFuncVar = 'x'; // Closure self-invoking function (function innerFunction (innerArg) { // begin of scope innerFunction // variable declared in innerFunction function scope var innerFuncVar = "y"; console.log( "outerArg = " + outerArg + "\n" + "outerFuncVar = " + outerFuncVar + "\n" + "innerArg = " + innerArg + "\n" + "innerFuncVar = " + innerFuncVar + "\n" + "globalVar = " + globalVar); }// end of scope innerFunction)(5); // Pass 5 as parameter }// end of scope outerFunction )(7); // Pass 7 as parameter innerFunction is closure that is defined inside outerFunction and has access to all variables declared and defined in the outerFunction scope. In addition, the function defined inside another function as a closure will have access to variables declared in the global namespace. Thus, the output of the code above would be: outerArg = 7 outerFuncVar = x innerArg = 5 innerFuncVar = y globalVar = abc

What is JavaScript Self-Invoking anonymous function or Self-Executing anonymous function.

A self-invoking anonymous function also called self-executing anonymous function runs immediately or automatically when we define it and self-invoking anonymous function doesn't have any name at all. Self-Invoking anonymous function syntax: (function() { console.log("Self-Invoking function code logic "); })(); Output: Self-Invoking function code logic We must have to know the fact that JavaScript functions run immediately when we put () after their names. function display() { console.log("Display me"); } display(); // This will run immediately Output: "Display me" /* This will not run immediately as we haven't put () after function name, function name is use full when we want to pass it as callback to another function or method. */ display; function testCallBack(callback) { callback (); // This will be call display method immediately if callback parameter is being set method display } testCallBack(display); // Here display function is being passed as callback

How to empty an array in JavaScript ?

For instance, var arrayList = ['a','b','c','d','e','f']; How can we empty the array above? There are a couple ways we can use to empty an array, so let's discuss them all. Method 1 arrayList = [] Above code will set the variable arrayList to a new empty array. This is recommended if you don't have references to the original array arrayList anywhere else, because it will actually create a new, empty array. You should be careful with this method of emptying the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged. For Instance, var arrayList = ['a','b','c','d','e','f']; // Created array var anotherArrayList = arrayList; // Referenced arrayList by another variable arrayList = []; // Empty the array console.log(anotherArrayList); // Output ['a','b','c','d','e','f'] Method 2 arrayList.length = 0; The code above will clear the existing array by setting its length to 0. This way of emptying the array also updates all the reference variables that point to the original array. Therefore, this method is useful when you want to update all reference variables pointing to arrayList. For Instance, var arrayList = ['a','b','c','d','e','f']; // Created array var anotherArrayList = arrayList; // Referenced arrayList by another variable arrayList.length = 0; // Empty the array by setting length to 0 console.log(anotherArrayList); // Output [] Method 3 arrayList.splice(0, arrayList.length); The implementation above will also work perfectly. This way of emptying the array will also update all the references to the original array. var arrayList = ['a','b','c','d','e','f']; // Created array var anotherArrayList = arrayList; // Referenced arrayList by another variable arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0 console.log(anotherArrayList); // Output [] Method 4 while(arrayList.length){ arrayList.pop(); } The implementation above can also empty arrays, but it is usually not recommended to use this method often.

What is function hoisting in JavaScript?

Function Expression var foo = function foo(){ return 12; }; In JavaScript, variable and functions are hoisted. Let's take function hoisting first. Basically, the JavaScript interpreter looks ahead to find all variable declarations and then hoists them to the top of the function where they're declared. For example: foo(); // Here foo is still undefined var foo = function foo(){ return 12; }; Behind the scene of the code above looks like this: javascript var foo = undefined; foo(); // Here foo is undefined foo = function foo(){ / Some code stuff } javascript var foo = undefined; foo = function foo(){ / Some code stuff } foo(); // Now foo is defined here

Write a mul function which will output when invoked as below syntax. console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48 Below is code followed by an explanation how it works: function mul (x) { return function (y) { // anonymous function return function (z) { // anonymous function return x * y * z; }; }; }

Here mul function accept the first argument and return anonymous function which take the second parameter and return anonymous function which take the third parameter and return multiplication of arguments which is being passed in successive. In Javascript function defined inside has access to outer function variable and function is a first class object so it can be returned by a function as well and passed as the argument in another function. A function is an instance of the Object type A function can have properties and has a link back to its constructor method Function can be stored as variable Function can be pass as a parameter to another function Function can be returned from function

What is the difference between a method and a function in javascript? A function is a piece of code that is called by name and function itself not associated with any object and not defined inside any object. It can be passed data to operate on (i.e. parameter) and can optionally return data (the return value). // Function definition function myFunc() { // Do some stuff; } // Calling function myFunc();

Here myFunc() function call is not associated with object hence not invoked through any object. A function can be self-invoking anonymous function or named self-invoking function // Named Self-invoking Function (function myFunc() { // Do some stuff; })(); // Anonymous Self-invoking Function (function() { // Do some stuff; })(); In a case of named self-invoking anonymous function or anonymous self-invoking function, there is no need of call function explicitly. A method is a piece of code that is called by name and that is associated with the object. In most respects it is identical to function call except for some key difference: It is implicitly passed for the object for which it was called. It is able to operate on data that is contained within the class (remembering that an object is an instance of a class- the class is the definition, the object is an instance of that) Method call is always associated with object var methodObject = { attribute: "xyz", display: function () { // Method console.log(this.attribute); } }; // Call method methodObject.display(); Here methodObject is an object and display is a method which is associated with methodObject.

What is the instanceof operator in JavaScript? What would be the output of the code below? function foo(){ return foo; } new foo() instanceof foo;

Here, instanceof operator checks the current object and returns true if the object is of the specified type. For Example: var dog = new Animal(); dog instanceof Animal // Output : true Here dog instanceof Animal is true since dog inherits from Animal.prototype. var name = new String("xyz"); name instanceof String // Output : true Here name instanceof String is true since dog inherits from String.prototype. Now let's understand the code below: function foo(){ return foo; } new foo() instanceof foo; Here function foo is returning foo, which again points to function foo. function foo(){ return foo; } var bar = new foo(); // here bar is pointer to function foo(){return foo}. So the new foo() instanceof foo return false; http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript

Difference between Function, Method and Constructor calls in JavaScript.

If your are familiar with Object-oriented programming, More likely familiar to thinking of functions, methods, and class constructors as three separate things. But In JavaScript, these are just three different usage patterns of one single construct. functions : The simplest usages of function call: function helloWorld(name) { return "hello world, " + name; } helloWorld("JS Geeks"); // "hello world JS Geeks" Methods in JavaScript are nothing more than object properties that reference to a function. var obj = { helloWorld : function() { return "hello world, " + this.name; }, name: 'John Carter' } obj.helloWorld(); // // "hello world John Carter" Notice how helloWorld refer to this properties of obj. Here it's clear or you might have already understood that this gets bound to obj. But the interesting point that we can copy a reference to the same function helloWorld in another object and get a difference answer. Let see: var obj2 = { helloWorld : obj.helloWorld, name: 'John Doe' } obj2.helloWorld(); // "hello world John Doe" You might be wonder what exactly happens in a method call here. Here we call the expression itself determine the binding of this this, The expression obj2.helloWorld() looks up the helloWorld property of obj and calls it with receiver object obj2. The third use of functions is as constructors. Like function and method, constructors are defined with function. function Employee(name, age) { this.name = name; this.age = age; } var emp1 = new Employee('John Doe', 28); emp1.name; // "John Doe" emp1.age; // 28 Unlike function calls and method calls, a constructor call new Employee('John Doe', 28) create a brand new object and passes it as the value of this, and implicitly returns the new object as its result. The primary role of the constructor function is to initialize the object.

How to check whether a key exist in a JavaScript object or not. Let say we have person object with property name and age var person = { name: 'Nishant', age: 24 } Now we want to check whether name property exist in person object or not ?

In JavaScript object can have own property, in above example name and age is own property of person object. Object also have some of inherited property of base object like toString is inherited property of person object. So how we will check whether property is own property or inherited property. Method 1: We can use in operator on objet to check own property or inherited property. console.log('name' in person); // checking own property print true console.log('salary' in person); // checking undefined property print false in operator also look into inherited property if it doesn't find property defined as own property. For instance If I check existence of toString property as we know that we haven't declared this property on person object so in operator look into there base property. Here console.log('toString' in person); // Will print true If we want to test property of object instance not inherited properties then we will use hasOwnProperty method of object instance. console.log(person.hasOwnProperty('toString')); // print false console.log(person.hasOwnProperty('name')); // print true console.log(person.hasOwnProperty('salary')); // print false

What is the difference between undefined and not defined in JavaScript?

In JavaScript, if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and script will stop executing. However, if you use typeof undeclared_variable, then it will return undefined. Before getting further into this, let's first understand the difference between declaration and definition. Let's say var x is a declaration because you have not defined what value it holds yet, but you have declared its existence and the need for memory allocation. > var x; // declaring x > console.log(x); //output: undefined Here var x = 1 is both a declaration and definition (also we can say we are doing an initialisation). In the example above, the declaration and assignment of value happen inline for variable x. In JavaScript, every variable or function declaration you bring to the top of its current scope is called hoisting. The assignment happens in order, so when we try to access a variable that is declared but not defined yet, we will get the result undefined. var x; // Declaration if(typeof x === 'undefined') // Will return true If a variable that is neither declared nor defined, when we try to reference such a variable we'd get the result not defined. > console.log(y); // Output: ReferenceError: y is not defined

What are the way by which we can create object in JavaScript ?

Method 1: Function Based If we want to create several similar objects. In below code sample, Employee which is called constructor function. This is similar to classes in object oriented languages. function Employee(fName, lName, age, salary){ this.firstName = fName; this.lastName = lName; this.age = age; this.salary = salary; } // Creating multiple object which have similar property but diff value assigned to object property. var employee1 = new Employee('John', 'Moto', 24, '5000$'); var employee1 = new Employee('Ryan', 'Jor', 26, '3000$'); var employee1 = new Employee('Andre', 'Salt', 26, '4000$'); Method 2: Object Literal Object Literal is best way to create an object and this is used frequently. Below is code sample for create employee object which contains property as well as method. var employee = { name : 'Nishant', salary : 245678, getName : function(){ return this.name; } } Below code sample is Nested Object Literal, Here address is an object inside employee object. var employee = { name : 'Nishant', salary : 245678, address : { addressLine1 : 'BITS Pilani', addressLine2 : 'Vidya Vihar'. phoneNumber: { workPhone: 7098889765, homePhone: 1234567898 } } } Method 3: Using JavaScript new keyword In below code sample object has been created using Object constructor function. var employee = new Object(); // Created employee object using new keywords and Object() employee.name = 'Nishant'; employee.getName = function(){ return this.name; } Note: As a best practices object literal way is used to create object over this method.

What is the drawback of creating true private methods in JavaScript?

One of the drawbacks of creating true private methods in JavaScript is that they are very memory-inefficient, as a new copy of the method would be created for each instance. var Employee = function (name, company, salary) { this.name = name || ""; //Public attribute default value is null this.company = company || ""; //Public attribute default value is null this.salary = salary || 5000; //Public attribute default value is null // Private method var increaseSalary = function () { this.salary = this.salary + 1000; }; // Public method this.dispalyIncreasedSalary = function() { increaseSlary(); console.log(this.salary); }; }; // Create Employee class object var emp1 = new Employee("John","Pluto",3000); // Create Employee class object var emp2 = new Employee("Merry","Pluto",2000); // Create Employee class object var emp3 = new Employee("Ren","Pluto",2500); Here each instance variable emp1, emp2, emp3 has its own copy of the increaseSalary private method. So, as a recommendation, don't use private methods unless it's necessary.

Write a function called deepClone which takes an object and creates a object copy of it. var newObject = deepClone(obj);

Solution: function deepClone(object){ var newObject = {}; for(var key in object){ if(typeof object[key] === 'object'){ newObject[key] = deepClone(object[key]); }else{ newObject[key] = object[key]; } } return newObject; } Explanation: We have been asked to do deep copy of object so What's basically it's mean ??. Let's understand in this way you have been given an object personalDetail this object contains some property which again a type of object here as you can see address is an object and phoneNumber in side an address is also an object. In simple term personalDetail is nested object(object inside object). So Here deep copy means we have to copy all the property of personalDetail object including nested object. var personalDetail = { name : 'Nishant', address : { location: 'xyz', zip : '123456', phoneNumber : { homePhone: 8797912345, workPhone : 1234509876 } } } So when we do deep clone then we should copy every property (including the nested object).

How do you check if an object is an array or not?

The best way to find out whether or not an object is an instance of a particular class is to use the toString method from Object.prototype: var arrayList = [1,2,3]; One of the best use cases of type-checking an object is when we do method overloading in JavaScript. For example, let's say we have a method called greet, which takes one single string and also a list of strings. To make our greet method workable in both situations, we need to know what kind of parameter is being passed. Is it a single value or a list of values? function greet(param){ if(){ // here have to check whether param is array or not }else{ } } However, as the implementation above might not necessarily check the type for arrays, we can check for a single value string and put some array logic code in the else block. For example: function greet(param){ if(typeof param === 'string'){ }else{ // If param is of type array then this block of code would execute } } Now it's fine we can go with either of the aforementioned two implementations, but when we have a situation where the parameter can be single value, array, and object type, we will be in trouble. Coming back to checking the type of an object, as mentioned previously we can use Object.prototype.toString if( Object.prototype.toString.call( arrayList ) === '[object Array]' ) { console.log('Array!'); } If you are using jQuery, then you can also use the jQuery isArray method: if($.isArray(arrayList)){ console.log('Array'); }else{ console.log('Not an array'); } FYI, jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not. In modern browsers, you can also use Array.isArray(arrayList); Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5

var k = 1; if (1) { eval(function foo(){}); k += typeof foo; } console.log(k);

The code above will also output 1undefined.

What will be the output of the code below? var bar = true; console.log(bar + 0); console.log(bar + "xyz"); console.log(bar + true); console.log(bar + false);

The code will output 1, "truexyz", 2, 1. Here's a general guideline for addition operators: Number + Number -> Addition Boolean + Number -> Addition Boolean + Number -> Addition Number + String -> Concatenation String + Boolean -> Concatenation String + String -> Concatenation

What is the difference between the function declarations below? var foo = function(){ // Some code }; function bar(){ // Some code };

The main difference is the function foo is defined at run-time whereas function bar is defined at parse time. To understand this in better way, let's take a look at the code below: Run-Time function declaration <script> foo(); // Calling foo function here will give an Error var foo = function(){ console.log("Hi I am inside Foo"); }; </script> <script> Parse-Time function declaration bar(); // Calling foo function will not give an Error function bar(){ console.log("Hi I am inside Foo"); }; </script> Another advantage of this first-one way of declaration is that you can declare functions based on certain conditions. For example: <script> if(testCondition) {// If testCondition is true then var foo = function(){ console.log("inside Foo with testCondition True value"); }; }else{ var foo = function(){ console.log("inside Foo with testCondition false value"); }; } </script> However, if you try to run similar code using the format below, you'd get an error: <script> if(testCondition) {// If testCondition is true then function foo(){ console.log("inside Foo with testCondition True value"); }; }else{ function foo(){ console.log("inside Foo with testCondition false value"); }; } </script>

What would be the output of the following code? function User(name) { this.name = name || "JsGeeks"; } var person = new User("xyz")["location"] = "USA"; console.log(person);

The output of above code would be USA. Here new User("xyz") creates a brand new object and created property location on that and USA has been assigned to object property location and that has been referenced by the person. Let say new User("xyz") crated a object called foo and returned now foo["location"] would be assigned value as USA and person is referencing to foo["location"].

What will be the output of the following code? var output = (function(x){ delete x; return x; })(0); console.log(output);

The output would be 0. The delete operator is used to delete properties from an object. Here x is not an object but a local variable. delete operators don't affect local variables.

What will be the output of the following code? var x = 1; var output = (function(){ delete x; return x; })(); console.log(output);

The output would be 1. The delete operator is used to delete the property of an object. Here x is not an object, but rather it's the global variable of type number.

What will be the output of the code below? var y = 1; if (function f(){}) { y += typeof f; } console.log(y);

The output would be 1undefined. The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). Therefore, inside the if statement, executing typeof f returns undefined because the if statement code executes at run time, and the statement inside the if condition is evaluated during run time.

What will be the output of the code below? var trees = ["xyz","xxxx","test","ryan","apple"]; delete trees[3]; console.log(trees.length);

The output would be 5. When we use the delete operator to delete an array element, the array length is not affected from this. This holds even if you deleted all elements of an array using the delete operator. In other words, when the delete operator removes an array element, that deleted element is not longer present in array. In place of value at deleted index undefined x 1 in chrome and undefined is placed at the index. If you do console.log(trees) output ["xyz", "xxxx", "test", undefined × 1, "apple"] in Chrome and in Firefox ["xyz", "xxxx", "test", undefined, "apple"].

What will be the output of the code below? // NFE (Named Function Expression var foo = function bar(){ return 12; }; typeof bar();

The output would be Reference Error. To make the code above work, you can re-write it as follows: Sample 1 var bar = function(){ return 12; }; typeof bar(); or Sample 2 function bar(){ return 12; }; typeof bar(); A function definition can have only one reference variable as its function name. In sample 1, bar's reference variable points to anonymous function. In sample 2, the function's definition is the name function. var foo = function bar(){ // foo is visible here // bar is visible here console.log(typeof bar()); // Work here :) }; // foo is visible here // bar is undefined here

What will be the output of code below? var salary = "1000$"; (function () { console.log("Original salary was " + salary); var salary = "5000$"; console.log("My New Salary " + salary); })();

The output would be undefined, 5000$. Newbies often get tricked by JavaScript's hoisting concept. In the code above, you might be expecting salary to retain its value from the outer scope until the point that salary gets re-declared in the inner scope. However, due to hoisting, the salary value was undefined instead. To understand this better, have a look of the code below: var salary = "1000$"; (function () { var salary = undefined; console.log("Original salary was " + salary); salary = "5000$"; console.log("My New Salary " + salary); })(); salary variable is hoisted and declared at the top in the function's scope. The console.log inside returns undefined. After the console.log, salary is redeclared and assigned 5000$.

What will be the output of the code below? var z = 1, y = z = typeof y; console.log(y);

The output would be undefined. According to the associativity rule, operators with the same precedence are processed based on the associativity property of the operator. Here, the associativity of the assignment operator is Right to Left, so typeof y will evaluate first , which is undefined. It will be assigned to z, and then y would be assigned the value of z and then z would be assigned the value 1.

What will be the output of the code below? var x = { foo : 1}; var output = (function(){ delete x.foo; return x.foo; })(); console.log(output);

The output would be undefined. The delete operator is used to delete the property of an object. Here, x is an object which has the property foo, and as it is a self-invoking function, we will delete the foo property from object x. After doing so, when we try to reference a deleted property foo, the result isundefined.

What will be the output of the code below? var Employee = { company: 'xyz' } var emp1 = Object.create(Employee); delete emp1.company console.log(emp1.company);

The output would be xyz. Here, emp1 object has company as its prototype property. The delete operator doesn't delete prototype property. emp1 object doesn't have company as its own property. You can test it console.log(emp1.hasOwnProperty('company')); //output : false. However, we can delete the company property directly from theEmployee object using delete Employee.company. Or, we can also delete the emp1 object using the __proto__ property delete emp1.__proto__.company.

Describe Singleton Pattern In JavaScript?

The singleton pattern is the most commonly used design pattern and one that you will probably is more than any others. It provides a great way to wrap the code into a logical unit that can be accessed through a single variable. The Singleton design pattern is used when only one instance of an object is needed throughout the lifetime of an application. In JavaScript, there is a different way to achieve singleton object than any other object oriented supported language (Java, C++). In JavaScript Singleton pattern have many uses, they can be used for NameSpacing, which reduce the number of global variables in your page (prevent from polluting global space), organizing the code in a consistent manner, which increase the readability and maintainability of your pages. There are two important points in the traditional definition of Singleton pattern: There should be only one instance allowed for a class and We should allow global point of access to that single instance Let me define singleton pattern in JavaScript context: It is an object that is used to create namespace and group together a related set of methods and attributes (encapsulation) and if we allow to initiate then it can be initiated only once. In JavaScript, we can create singleton though object literal. However, there is some another way but that I will cover in next post. A singleton object consists of two parts: The object itself, containing the members (Both methods and attributes) within it, and global variable used to access it. The variable is global so that object can be accessed anywhere in the page, this is a key feature of the singleton pattern. JavaScript: A Singleton as a Namespace As I have already stated above that singleton can be used to declare Namespace in JavaScript. NameSpacing is a large part of responsible programming in JavaScript. Because everything can be overwritten, and it is very easy to wipe out variable by mistake or a function, or even a class without even knowing it. A common example which happens frequently when you are working with another team member parallel, function findUserName(id) { } /* Later in the page another programmer added code */ var findUserName = $('#user_list'); /* You are trying to call :( */ console.log(findUserName()) One of the best ways to prevent accidentally overwriting variable is to namespace your code within a singleton object. /* Using Namespace */ var MyNameSpace = { findUserName : function(id) {}, // Other methods and attribute go here as well } /* Later in the page another programmer added code */ var findUserName = $('#user_list'); /* You are trying to call and you make this time workable */ console.log(MyNameSpace.findUserName());

If we have a JavaScript associative array var counterArray = { A : 3, B : 4 }; counterArray["C"] = 1; How can we calculate the length of the above associative array's counterArray?

There are no in-built functions and properties available to calculate the length of associative array object here. However, there are other ways by which we can calculate the length of an associative array object. In addition to this, we can also extend an Object by adding a method or property to the prototype in order to calculate length. However, extending an object might break enumeration in various libraries or might create cross-browser issues, so it's not recommended unless it's necessary. Again, there are various ways by which we can calculate length. Object has the keys method which can be used to calculate the length of an object: Object.keys(counterArray).length // Output 2 We can also calculate the length of an object by iterating through an object and by counting the object's own property. function getSize(object){ var count = 0; for(key in object){ // hasOwnProperty method check own property of object if(object.hasOwnProperty(key)) count++; } return count; } We can also add a length method directly on Object: Object.length = function(){ var count = 0; for(key in object){ // hasOwnProperty method check own property of object if(object.hasOwnProperty(key)) count++; } return count; } //Get the size of any object using console.log(Object.length(counterArray))

Best way to detect undefined object property in JavaScript. Suppose we have given an object person var person = { name: 'Nishant', age : 24 } Here the person object has a name and age property. Now we are trying to access the salary property which we haven't declared on the person object so while accessing it will return undefined. So how we will ensure whether property is undefined or not before performing some operation over it?

We can use typeof operator to check undefined if(typeof someProperty === 'undefined'){ console.log('something is undefined here'); } Now we are trying to access salary property of person object. if(typeof person.salary === 'undefined'){ console.log("salary is undefined here because we haven't declared"); }

Best way to detect undefined object property in JavaScript. Suppose we have given an object person var person = { name: 'Nishant', age : 24 } here person object has name and age property. Now we are trying to access salary property which we haven't declared on person object so while accessing it will return undefined. So how we will ensure whether property is undefined or not before performing some operation over it.

We can use typeof operator to check undefined if(typeof someProperty === 'undefined'){ console.log('something is undefined here'); } Now we are trying to access salary property of person object. if(typeof person.salary === 'undefined'){ console.log("salary is undefined here because we haven't declared"); }

What is undefined x 1 in JavaScript? var trees = ["redwood","bay","cedar","oak","maple"]; delete trees[3];

When you run the code above and type console.log(trees); into your Chrome developer console, you will get ["redwood", "bay", "cedar", undefined × 1, "maple"]. When you run the code in Firefox's browser console, you will get ["redwood", "bay", "cedar", undefined, "maple"]. Thus, it's clear that the Chrome browser has its own way of displaying uninitialised indexes in arrays. However, when you check trees[3] === undefined in both browsers, you will get similar output as true. Note: Please remember you do not need to check for the uninitialised index of array in trees[3] === 'undefined × 1', as it will give you an error. 'undefined × 1' is just way of displaying an array's uninitialised index in Chrome.

Write a function called Clone which takes an object and creates a object copy of it but not copy deep property of object. var objectLit = {foo : 'Bar'}; var cloneObj = Clone(obj); // Clone is the function which you have to write console.log(cloneObj === Clone(objectLit)); // this should return false console.log(cloneObj == Clone(objectLit)); // this should return true

function Clone(object){ var newObject = {}; for(var key in object){ newObject[key] = object[key]; } return newObject; }

Write a mul function which will produce the following outputs when invoked:

javascript console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48 Below is the answer followed by an explanation to how it works: function mul (x) { return function (y) { // anonymous function return function (z) { // anonymous function return x * y * z; }; }; } Here the mul function accepts the first argument and returns an anonymous function, which takes the second parameter and returns another anonymous function that will take the third parameter and return the multiplication of the arguments that have been passed. In JavaScript, a function defined inside another one has access to the outer function's variables. Therefore, a function is a first-class object that can be returned by other functions as well and be passed as an argument in another function. A function is an instance of the Object type A function can have properties and has a link back to its constructor method A function can be stored as a variable A function can be pass as a parameter to another function A function can be returned from another function


Related study sets

managing people and organizations test 4

View Set

Lewis Ch. 17 - Preoperative Care

View Set

BIOL 2721 HW 10 AUTONOMIC NERVOUS SYSTEM

View Set

Intro to Companion animals exam 2

View Set