Template literals.
If you are working with multi-line string,
use the backtick(``) instead of using quotes('').
When we use quotes with multi-
line string we need to use the concatenation operator (+) and newline(\n) character.
line string we need to use the concatenation operator (+) and newline(\n) character.
Whereas Backtick(`) concatenates the string parts into a single string. It is called as Template literals.
...............................................................................................................................................................................................................
return length
ans: 4
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
undefined, 20,2
...............................................................................................................................................................................................................
orange, orange
var does not consider block scopes {}.
var does not consider block scopes {}.
...............................................................................................................................................................................................................
Variables In JavaScript
Variables In JavaScript
A variable is a container or portion of memory to store some data value temporarily to use somewhere in the program later(it may be changed during the program execution).
A variable is identified by some identifier(unique) and some value is assigned by the assignment operator. An identifier is the valid sequence of characters for JavaScript. It is mandatory to declare a variable before using it.
Creating the variable in JavaScript
javascript variable
var x=10;
var b="Welcome to JavaScript";
var f=13.26;
var b="Welcome to JavaScript";
var f=13.26;
What are the rules for Naming Variables in JavaScript?
- The variable name can not contain spaces.
- The first character of the variable name must be a letter or an underscore (_) or dollar sign ($).
- The remaining name of the variable name may contain any letter, number, dollar or the underscore. Other characters including spaces, symbols, and punctuation marks are not allowed in the variable name.
- JavaScript is a case sensitive language it means variable names are also case sensitive OR variable name Lastname and LastName are different.
- There's no limit to the length of the variable name.
- Any of the JavaScript's reserved keywords can not be used as a variable name.
We can declare a variable in JavaScript
var k;
var name;
but, if we use them then they still have a value undefined. Variables in JavaScript can obtain several types like number, string or boolean. Once we provide them some value then we will obtain that value
k=12;
name="Harry";
We can also re-declare the variables, like
var name=50;
document.write(name);
var name="Harry";
...............................................................................................................................................................................................................
# 1 How to run getB() method
const obj ={
a:11,
b:22,
getA(){
console.log(this.a)
},
getB (){
console.log(this.a)
}
}
obj.getA().getB()
...............................................................................
Ans:
const obj ={
a:11,
b:22,
getA(){
console.log(this.a)
return this
},
getB (){
console.log(this.a)
}
}
obj.getA().getB()
..........................................................................................................................................................................................................................
Object
3 Ways To Access Object Properties in JavaScript
objectName.propertyName
objectName['properyName']
1. Dot property accessor
2. Square brackets property accessor
hero['name'] and hero[property] both read the property name by using the square brackets syntax.
Choose the square brackets property accessor when the property name is dynamic, i.e. determined at runtime.
3. Object destructuring
The basic object destructuring syntax is pretty simple:
How to Remove Array Duplicates in ES6
Set Convert Set to an Array using Array.from
Alternatively, you can also use Array.from to convert a Set into an array:
First, we are creating a new Set by passing an array.
Because Set only allows unique values, all duplicates will be removed.
Now the duplicates are gone, we’re going to convert it back to an array by using the spread operator ...
...............................................................................................................................................................................................................
Array
...............................................................................................................................................................................................................
Ans - Undefind
...............................................................................................................................................................................................................
...............................................................................................................................................................................................................
Why Is Array/Object Destructuring So Useful And How To Use It
Example : #1
Example: #2
Example: #3
Example: #4
Example: # 5 destructuring spread operators (display rest of array)
Example: #6
Example: #7
Example: #8
Example: #9
Destructuring object ={}
Destructuring Array =[]
Example: #10
Example: #11
Example: #12
Example: #12
Example: #13 [JavaScript Interview Questions]
(function(){
var a=b=3
a=b=3
// call that way e
b=3 // global scope
var a=b //functional scope
})()
console.log(typeof a) // undefind
console.log(typeof b) //number
console.log(typeof a) // number
console.log(typeof b) // number
Example: #14
.........................................................................................................................................................................................................................
Top 13 useful JavaScript Array Tips for Developers
Here are the top 13 useful JavaScript array methods for developers.
How to remove duplicates from an array
How to change a particular value in an array
How to use Map array without .map()
To empty an array
How to convert an array to an object
How to fulfill an array with data
How to merge arrays
How to find the intersection of two arrays
How to remove falsy values from an array
How to get random value form the array
How to reverse an array
JavaScript's .lastIndexOf() method
How to sum all the values in the array
1. How to remove duplicates from an array
It's a famous inquiry question about Javascript arrays, how to remove the exceptional qualities from Javascript array. Here is a snappy and simple answer for this issue, you can utilize another Set() for this reason. What's more, I might want to give both of you potential approaches to do it, one with .from() strategy and second with spread administrator (…).
var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];
// First method
var uniqueFruits = Array.from(new Set(fruits))
console.log(uniqueFruits); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”]
// Second method
var uniqueFruits2 = […new Set(fruits)];
console.log(uniqueFruits2); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”]
2. How to change a particular value in an array
Some of the time it's important to supplant particular esteem in the array while making code, and there is a decent short strategy to do it which you probably won't know yet. For this, we may utilize .splice(start, worth to expel, valueToAdd) and go there every one of the three parameters indicating where we need to begin alteration, what number of qualities we need to change and the new qualities.
var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];
fruits.splice(0, 2, “potato”, “tomato”);
console.log(fruits); // returns [“potato”, “tomato”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”]
"Why JavaScript is Compulsory for Modern Web Development?"
3. How to use Map array without .map()
Most likely everybody knows .map() technique for arrays, however, there is an alternate arrangement that might be utilized to get a comparative impact and very spotless code also. We can use .from() technique for this reason.
var friends = [
{ name: ‘John’, age: 22 },
{ name: ‘Peter’, age: 23 },
{ name: ‘Mark’, age: 24 },
{ name: ‘Maria’, age: 22 },
{ name: ‘Monica’, age: 21 },
{ name: ‘Martha’, age: 19 },
]
var friendsNames = Array.from(friends, ({name}) => name);
console.log(friendsNames); // returns [“John”, “Peter”, “Mark”, “Maria”, “Monica”, “Martha”]
4. To empty an array
Do you have an array brimming with components yet you have to clean it for any reason, and you would prefer not to expel things individually? It's extremely easy to do it in one line of code. To discharge an array, you have to set an array's length to 0, and that is it!
var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];
fruits.length = 0;
console.log(fruits); // returns []
5. How to convert an array to an object
It happens that we have an array, yet for some reason, we need an article with this information, and the quickest method to change over the array into an item is to utilize a notable spread administrator (… ).
var fruits = [“banana”, “apple”, “orange”, “watermelon”];
var fruitsObj = { …fruits };
console.log(fruitsObj); // returns {0: “banana”, 1: “apple”, 2: “orange”, 3: “watermelon”, 4: “apple”, 5: “orange”, 6: “grape”, 7: “apple”}
6. How to fulfill an array with data
There are a few circumstances when we make an array, and we might want to fill it with certain information, or we need an array with similar qualities, and for this situation .fill() strategy accompanies a simple and clean arrangement.
var newArray = new Array(10).fill(“1”);
console.log(newArray); // returns [“1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”]
7. How to merge arrays
Do you realize how to union arrays into one array not utilizing .concat() technique? There is a basic method to consolidate any measure of arrays into one out of one line of code. As you presumably acknowledged previously spread administrator (… ) is quite valuable while working with arrays and it's the equivalent of this situation.
var fruits = [“apple”, “banana”, “orange”];
var meat = [“poultry”, “beef”, “fish”];
var vegetables = [“potato”, “tomato”, “cucumber”];
var food = […fruits, …meat, …vegetables];
console.log(food); // [“apple”, “banana”, “orange”, “poultry”, “beef”, “fish”, “potato”, “tomato”, “cucumber”]
8. How to find the intersection of two arrays
It's additionally one of the most well-known difficulties which you can look at any Javascript meet since it appears on the off chance that you can utilize array strategies and what is your rationale. To discover the convergence of two arrays, we will utilize one of the recently demonstrated strategies in this article, to ensure that qualities in the array we are checking are not copied and we will utilize .channel strategy and .incorporates technique. Subsequently, we will get the array with values that were introduced in the two arrays. Check the code:
var numOne = [0, 2, 4, 6, 8, 8];
var numTwo = [1, 2, 3, 4, 5, 6];
var duplicatedValues = […new Set(numOne)].filter(item => numTwo.includes(item));
console.log(duplicatedValues); // returns [2, 4, 6]
"Top Web Designing Hacks and Trends for Web Development"
9. How to remove falsy values from an array
From the start, how about we characterized falsy values. In Javascript, falsy qualities are false, 0, „", invalid, NaN, unclear. Presently we can discover how to expel this sort of qualities from our array. To accomplish this, we are going to utilize the .channel() strategy.
var mixedArr = [0, “blue”, “”, NaN, 9, true, undefined, “white”, false];
var trueArr = mixedArr.filter(Boolean);
console.log(trueArr); // returns [“blue”, 9, true, “white”]
10. How to get random value form the array
In some cases, we have to choose an incentive from the array arbitrarily. To make it in a simple, quick, and short way and keep our code clean we can get an irregular file number as indicated by the array length. How about we see the code:
var colors = [“blue”, “white”, “green”, “navy”, “pink”, “purple”, “orange”, “yellow”, “black”, “brown”];
var randomColor = colors[(Math.floor(Math.random() * (colors.length)))]
11. How to reverse an array
At the point when we have to flip our array, there is no compelling reason to make it through the muddled circles and capacities, there is a simple array technique that does it for us, and with one line of code, we may have our array turned around. We should check it:
var colors = [“blue”, “white”, “green”, “navy”, “pink”, “purple”, “orange”, “yellow”, “black”, “brown”];
var reversedColors = colors.reverse();
console.log(reversedColors); // returns [“brown”, “black”, “yellow”, “orange”, “purple”, “pink”, “navy”, “green”, “white”, “blue”]
12. JavaScript's .lastIndexOf() method
In Javascript, there is a fascinating technique that permits finding the record of the last event of the given component. For instance, if our array has copied values, we can discover the situation of its last event. How about we see the code model:
var nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7];
var lastIndex = nums.lastIndexOf(5);
console.log(lastIndex); // returns 9
13. How to sum all the values in the array
Another test that happens all the time during Javascript Engineer interviews. Nothing frightening comes here; it tends to be unraveled utilizing .diminish technique in one line of code. How about we look at the code:
var nums = [1, 5, 2, 6];
var sum = nums.reduce((x, y) => x + y);
console.log(sum); // returns 14
.........................................................................................................................................................................................................................................
Ways To Use “Console” Object
Now you can easily read the values by printing it in the form of a table.
.........................................................................................................................................................................................................................................
3, 3, 1, 0, NaN
.........................................................................................................................................................................................................................................
.........................................................................................................................................................................................................................................
.........................................................................................................................................................................................................................................
How to create JavaScript objects using different methods
Today, we are going to learn about creating JavaScript objects using various methods given below.
1. Object Literals.
2. Constructor Functions.
3. Object.create().
4. ECMAScript 6 Classes.
Let us understand them in detail.
1. Object Literals
var student = {name: 'Ross', rollno: 1}
student.name
Example -
var name ={
firstName :'sapan',
lastNamr:'Das '
}
console.log(name.firstName) // sapan
2. Constructor Functions
[ new keyword with a function name ]
function Student(name, age) {
this.name = name;
this.age = age;
}
var ross = new Student('Ross', 1);
var david = new Student('David', 2);
console.log(ross)
console.log(david)
The this keyword refers to an object.
ECMAScript 6 Classes
class Student {
constructor(name, rollno) {
this.name = name;
this.rollno = rollno;
}
getStudentDetails() {
return "Student: " + this.name + ", Roll No: " + this.rollno;
}
}
var ross = new Student("Ross", 1);
document.write(ross.getStudentDetails());
Object.create()
We could create the same objects using the object.create() syntax as follows.
var ross = Object.create(Object.prototype, {
name: {
value: 'ross',
enumerable: true,
writable: true,
configurable: true
},
rollno: {
value: 1,
enumerable: true,
writable: true,
configurable: true
}
});
HOISTING [ JavaScript Hoisting ]
JavaScript Hoisting
Hoisting is JavaScript's default behavior of placing declarations at the top.
In JavaScript, a variable can be declared after it has been used it means a variable can be used before it has been declared.
Example :#1
x = 5;
document.getElementById("demo").innerHTML=x;
var x;
is equivalent to,
Johnyundefined
.........................................................................................................................................................................................................................................
var x;
x = 5;
x = 5;
document.getElementById("demo").innerHTML=x;
Initializations
The variable initializations are not hoisted, only declarations are hoisted.
Example :#2
<html>
<head>
<script>
name1='Johny';
name2='Johny';
document.getElementById("demo").innerHTML=name1+name2;
var name1;
var name2;
</script>
</head>
<body>
<button onclick="testPrompt()">Click me</button>
<div id='demo'></div>
</body>
</html>
will result
JohnyJohny
but the following code.
Example :#3
<html>
<head>
<script>
name1='Johny';
document.getElementById("demo").innerHTML=name1+name2;
name2='Johny';
var name1;
var name2;
</script>
</head>
<body>
<button onclick="testPrompt()">Click me</button>
<div id='demo'></div>
</body>
</html>
will result
Tips
The variable name1 and name 2 are hoisted at the top, but not their initialization,
so we are getting the name2 value "undefined".
However, name2 is initialized,
It is always best practice to declare variables first and use them later.
let and const Hoisting
The "let" and "const" variables are not hoisted.
Function Hoisting
Functions are hoisted like variables and function declarations are kept at the top most place during the compilation. The following code,
will result
Function F1 Function F2
Example :#4
.........................................................................................................................................................................................................................................
.........................................................................................................................................................................................................................................
No comments:
Post a Comment