fabiochiu/medium-articles huggingface dataset:
Things you should know if you are JavaScript Programmer
Tags: Javascript Tips, JavaScript

JavaScript is the most used programming language for Web Development. Many people using JavaScript most often forget about the basics of JavaScript. In this post i will try to jog down your memory of JavaScript and some fundamental concepts in JavaScript.

Primitive Data Types in JavaScript

There are seven primitive data types in JavaScript :-

Boolean: A boolean represent a logical entity and can have two values: true and false. Any variable or object which has a value are defined as true. ‘0’, ‘NaN’, ‘undefined’, empty string, null are treated as false. Number: A number in JavaScript contains both integer and decimals(floating point number). They are stored in double-precision 64-bit binary format IEEE 754. Integers are correct up to 15 digits. Floating points are not always accurate. Maximum number of decimals is up to 17 digits. BigInt: For values greater than 2⁵³-1 BitInt can be used.You can create bigInt by appending n at the end of the number. String: String data type is used to represent, store and manipulate textual data. JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. Null: Null is intentional absence of value. Null is an object type. Null is equal to undefined but not identical Undefined: When a value has not been assigned to the variable then it has the value undefined. Symbol: A value having the data type Symbol can be referred to as a “Symbol value”. In a JavaScript runtime environment, a symbol value is created by invoking the function Symbol, which dynamically produces an anonymous, unique value. A symbol may be used as an object property.

Static Typing and Dynamic Typing

JavaScript is dynamic type. It means that the interpreter assigns variable a type at the runtime based on the value of variable. Languages like C, C++, Java are Static type. Their variables need to be defined data type before execution of the program.

Memory allocation for primitive type and Object type

In JavaScript primitive data are stored in a memory space called stack. So they are quicker to access. While coping values of primitive type, new data is created. Object type are stored in Heap and takes a little time to access. Copies created are shallow copies(two object point towards the same data). To create deep copies we can use property Object.assign()
JS Shorts — Prototypal Inheritance
By: Prakhar Jaiswal
Tags: Javascript Development, Javascript Tips, Prototype, JavaScript

The way of extending the common properties from one object to another though their prototype property is called prototypal inheritance.

The inheritance in JavaScript is a bit different from other languages. It’s more of a delegation rather than inheriting the properties. Everything in JavaScript is an Object in essence. Each of these objects holds a __proto__ property that is a reference to another object, which is called the object’s prototype. When a property is accessed on an object and if it’s not found on that object, the JavaScript engine looks for that property in the object’s __proto__ property. If it’s not found here, then it looks in the __proto__ 's __proto__ property and so on until it reaches the end of the prototype chain. This behaviour is what we refer to as Prototypal Inheritance in JavaScript.

Notice how we are able to access the login method from Admin even though it’s not defined there. This is possible due to the Prototypal Inheritance.

Notice the structure of both the objects. The userOne’s __proto__ has the login method and admin’s __proto__ has the deleteUser method along with another __proto__ property which points to the User’s __proto__ property.

Image by LEEROY Agency from Pixabay

— That’s all for today
당신이 알아야 할 자바스크립트의 강력한 7가지 팁
Tags: Javascript Tips, JavaScript, Web Development, Programming, Coding

5 Fun APIs for Your Next JavaScript Projects

5 useful APIs that you can use in your JavaScript projects
Scopes in Javascript
By: Md Shahab Uddin
Tags: Javascript Tips, JavaScript, Javascript Development, Web Development, Web Design

Photo by Bruno Berger on Unsplash

The scope is a term which decides which variable is accessible from which position. It decides the accessibility of variables. There are many kinds of scope.

Global scope: They are accessible from anywhere of the code

Local scope: It is mainly of two types as Function scope and blocks scope.

Function scope: Anything declared inside a function is inaccessible from the outside of the function.

Block scope: IF you declare something inside if/for/while block, it creates a block scope. Anything inside a curly brace is a block scope. But remember that only let and const can be used to create block scope. Using var will not create a block scope.

Public and private scope:

We can create a public and private scope using namespace.

Let’s create a private scope by wrapping it with braces and call immediately.

In the above code, the sing function is unavailable because it is in a private scope. Let's create a module where we will define both public and private scope and stop polluting the global environment.

Here all the methods inside the return are public and accessible from outside. But private methods are inaccessible.

Private methods aren’t accessible but private methods are accessible inside the private method.

This is another way of writing private and public scope.

Remember that the private method is usually started with an underscore sign.

Another way of writing public and private methods is to declare an object and add a method to it. At last return this object. Here is the example

IF we try “module. eat()”, it will return an error because it is a private function and it isn’t accessible.

Some facts

The scope can be nested. There can be multiple scopes. We can call it a scope chain.

Lexical scope, static scope, and closure is the same thing

By creating two different functions we can create two scopes and use the same name in both two scopes and they will not clash so that we can isolate them.

Thanks for reading. Follow me for more articles
How to Fully Copy an External React Component (Including Static Properties)
By: Curt Toppel
Tags: Object Assign, Javascript Tips, JavaScript, React, React Tips

I just recently faced a challenging moment where I had an external component that I wanted to add default properties to based on my project. I created a new function component and my code looked like this:

My project had an error however which came down to the external component having static properties on it, namely Group which was being called in my code as Button.Group. The problem with the above code is that the references to the static props were lost in my “copy”.

I found that I just needed to add the property to my “copy” and it worked for this use case.

The problem with adding individual properties to the “copy” is that not only do I have to know what all the external component’s properties are, but even if I did, it would be pretty cumbersome and repetitive if there were many.

This is why I ended up solving the issue by assigning all the original properties to my “copy” which finally resulted in a full copy of the external component.

Final version

If anyone knows of an even simpler/cleaner way of doing this, please let me know!
It’s a great article!
By: Emmanuel Unyime
Tags: JavaScript, Javascript Tips, Web Development

Are you a JavaScript developer who uses console.log() often to debug your code? There is nothing wrong in it. But if you are unaware, there are so many other methods of console object which are quite amazing. …
An Introduction to The Geolocation API in JavaScript
By: Mehdi Aoussiad
Tags: Javascript Tips, JavaScript, Web Development, Programming, Coding

An Introduction to The Geolocation API in JavaScript

Photo by henry perks on Unsplash

Introduction

The geolocation API is used to get the geographical position of a user. It is a simple way to get the latitude and the longitude of a user on your website. However, since this can compromise privacy, the position is not available unless the user approves it.

In this article, we will learn about the geolocation API in JavaScript and how we can use it. Let’s get right into it.

Using the geolocation API

The geolocation API is supported in all browsers and will only work on secure contexts as HTTPS. If your website is hosted on a non-secure origin (such as HTTP), the requests to get the user's location will no longer function.

The method getCurrentPosition() is used to return the user's position.

Here is an example:

function getLocation() { // Check if geolocation is supported.

if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(showPosition); // If not supported.

} else {

console.log("Geolocation is not supported by this browser.");

}

} function showPosition(position) {

const x = position.coords.latitude;

const y = position.coords.longitude;

console.log(x); // Returns your latitude.

console.log(y); // Returns your longitude.

}

As you can see above, the first function will check if the geolocation is supported. If so, it will run the function getCurrentPosition , otherwise, it will display a message to the user.

If the method getCurrentPosition is successful, it returns a coordinates object to the function specified in the parameter showPosition . The function showPosition() outputs the Latitude and the Longitude.

Now, you can display the user’s location on the web page if you want.

Displaying the result in a map

You can also display the results on a map using the geolocation API. You only need to access a map service, like Google Maps.

In the example below, the returned latitude and longitude are used to show the location in a Google Map (using a static image):

function showPosition(position) {

var latlon = position.coords.latitude + "," +position.coords.longitude;



var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=

"+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";



const map = document.getElementById("mapholder");

map.innerHTML = "<img src='"+img_url+"'>";

}

Conclusion

This was just an introduction to a cool JavaScript API, I encourage you to explore more information about this API by visiting the MDN documentation.

Thank you for reading this article, I hope you found it useful.

More Reading
Five Reason Why I Love Javascript
By: Bipin Parajuli
Tags: Javascript Tips, JavaScript, React, Node, Web Development

It has been a year I am learning Javascript so I found many reasons to learn Javascript over other languages. Here I would mention some of them:

Easy to Learn

JavaScript is comparatively easy to learn than other programming languages. It’s beginner-friendly and anyone can start learning it without any previous experience in coding. On the begging day, I started java I struggle with some environment setup or set up in the code editor to run the program. But with JavaScript, I didn’t have to work much on setup and other stuff.

2. Versatile

Isn’t it cool to run a single language everywhere? Javascript Framework and libraries like React, Angular, Vue can be used to build front-end applications. With the help of nodejs, expressjs we can build the server-side of the application with the same language. Moreover, javascript can be used to build android and iOS applications, game development, IoT, desktop applications, and big data.

3. Easy Create Visual Effects and Other Eye-catching Aesthetic Features

There’s building a web page, and then there’s building a visually appealing web page that attracts the user’s attention and encourages interaction. JavaScript is so versatile that you can use it to easily add cool design elements such as animation, interactive maps, and scrolling video.

4.Node and npm

This could be the pretty silly reason for choosing javascript. There are over one million package in the npm. Which make the life of javascript programmer easy. We can simply used build in module in our code by installing npm and npm packages.

5. High Community support and growing popularity

According to the Stackoverflow survey 2020 javascript is a number one programming language. Many of companies are sifting them towards modern techonogies like javascript. There are hugh support for javascript to find the solution of a problem. Plenty of ready to use resouce and solutions can be found in google and youtube for javascript developers.
Javascript: IIFE
By: Deepak Jha
Tags: Javascript Development, Javascript Tips, ES6, JavaScript

In this blog, I will try to share my knowledge about the IIFE which stands for Immediately Invoked Function Expression.

As you already know, Global variables are bad because they can cause a lot of problems, and in modern javascript, we avoid this global variable problem by IIFE.

It is a function expression that looks like this,

output

And don't be confused because you already know this, what javascript engine will do with this code.

IIFE is a common javascript design pattern used by a lot of popular libraries like jquery etc. and the idea behind using this pattern is to place all the library code inside the local scope to avoid any namespace collision.

The first thing you should know is, by declaring ( ) we are saying to the javascript engine, this is not a function declaration, it's a function expression and after that, we created an anonymous function with no name, and then we immediately invoked this function.

Now you must be thinking what's the benefit of doing this?

So the main benefit of IIFE is we can define global properties inside the anonymous function and that will be scoped inside that IIFE only.

Example

While executing this code, the javascript engine will create a new execution context that has a new Variable Environment scope and this allows us to attach private data right in Variable Environment that can be accessed by Global execution Context.

As you can see from examples, it takes advantage of scopes, they enable us to attach private data to a function and create a fresh environment for us so we don't pollute our Global Execution Context. As we add more and more javascript files we want to make sure that we can wrap things in a function to scope things into their own environments and minimize the amount of data we place in the Global Execution Context.
A Beginner’s Guide To JavaScript Primitive vs. Reference Values
By: Nasar Uddin
Tags: Javascript Tips, JavaScript, Oop, Web Development, Programming

In JavaScript, a variable may store two types of values: primitive and reference.

Primitive types

JavaScript provides six primitive types as undefined, null, boolean, number, string, and symbol.

The size of a primitive value is fixed, therefore, JavaScript stores the primitive value on the stack. When you assign a variable to this type, the variable extract the value. If you change the value the variable becomes the new value, that’s it. Let’s see some example-

let x = 10;

let y = x; // y extract the value of x

print(x, y); // 10 10

x = 20;

print(x, y); // 20 10

y = 15;

print(x, y); // 20 15

In this example, at line 4 we modify the value of x. But the change didn’t affect the value of y. Because y extract the value of x.

Reference types

There are two reference type, they are Array and Objects (as Array are Objects so technically just one type).

The size of a reference value is dynamic so JavaScript stores the reference value on the heap. When we create a new object the value is not directly assigned to a variable. Instead, a reference is set to the variable. Let’s see an example-

let person1 = {name: "Jhon", age: 30};

let person2 = person1;

console.log(person1); // {name: "Jhon", age: 30}

console.log(person2); // {name: "Jhon", age: 30}

person2.name = "Json";

console.log(person1); // {name: "Json", age: 30}

In this example, we only modified person2. But person1 also did modify. Because of person1 and person2 both reference {name: “Jhon”, age: 30} this object instead of having actual value. So, modification of any object with modifying the actual object either it is person1 or person2.

Solving the problem

When we changed the name of person2, it modified the original object. So, instead of referencing the original object, we need to create a new reference for the new object. This way the new object will point to its own object instead of overlapping each other. We can create new object reference with the help of spread operator. Let’s see an example-

let person1 = {name: "Jhon", age: 30};

let person2 = {...person1};

console.log(person1); // {name: "Jhon", age: 30}

console.log(person2); // {name: "Jhon", age: 30}

person2.name = "Json";

console.log(person1); // {name: "Jhon", age: 30}

console.log(person2); // {name: "Json", age: 30}

This way we can solve the overlapping problem of reference type.

Thanks

Nasar.
Objects having string keys are executed faster.
By: Mayank Gupta
Tags: Javascript Tips

Objects having string keys are executed faster.

Yes that is true.For example-

A:

const obj1 = {

“name”:”Mayank”

}

B:

const obj2 = {

name:”Mayank”

}

The execution time of A is less as compared to B.Here is the screenshot-

Execution time for object A and object B

The reason behind this is that all object keys (excluding Symbols) are strings under the hood, even if you don’t type it yourself as a string.So for object B javascript converts the keys present in object to string then execute it while for object A the keys are already string.

Thank you.
Building a Simple Drum Kit with Vanilla JavaScript
By: Mehdi Aoussiad
Tags: Javascript Tips, Front End Development, JavaScript, Web Development, Programming

Building a Simple Drum Kit with Vanilla JavaScript

Photo by Carlos Coronado on Unsplash

Introduction

The Drum Kit is one of the exciting things that you can build with JavaScript in the browser. Last month, I built a simple drum kit, it was one of the projects that I have tried in my 100 days of code challenge. So if you are a beginner, this is a good project to test your skills.

Before trying this project, you will need to have basic knowledge of HTML, CSS, and JavaScript. Let’s get right into it.

The Project Demo

Drum Kit.

As you can see in the example above, the project is very simple. You press the key on your keyboard, then you get a drum kit song playing. We have also added a simple animation when you press the keys.

Let’s start with HTML

First, we will place everything inside a div with a class of container , then we will put our divs for the squares that contain letters. And for each div, we will add an ID that represents the keyCode of each letter inside the div. You will know about that when we will get to the JavaScript part. After the container div, we will put all our drum kit songs with an ID that represents the keyCode of the letter that we are going to press in order to play that particular audio.

Have a look at the example below:

The HTML Structure.

Let’s style our elements

So now, we will style our elements using CSS. You can read the code below to see our stylesheet.

Styling Our Elements with CSS.

The JavaScript part

Now, this is the exciting part that will make our project functional. In our JavaScript logic, we selected all the audio elements and all the divs inside the container div using querySelectorAll() , because we will handle them using the method forEach() .

After that, we have added an event listener that will take two arguments: the event keydown and the callback function that will also take the event object as a parameter.

Here is an example:

window.addEventListener('keydown', (e) =>{

console.log(e.keyCode);

}

// When you press a letter on your keyboard, it will print the keycode of that letter in the console.

That is why in our HTML, we have added the ID(keyCode) for each div and for each audio. When you press a letter that has the same ID as an audio element, it will play that specific audio element.

You can read the code below carefully to understand our logic:

Our JavaScript Code.

Now congratulations, you have easily created a simple Drum Kit project with Vanilla JavaScript.

Conclusion

The best way to become a good developer is by practicing what you have learned. Practice makes perfect. Building a simple Drum Kit will help you practice and improve your coding skills in general.

Thank you for reading this article, I hope you found it useful.

More Reading
Determining real data types in Javascript using Object.prototype.toString
By: Sunil Chaudhary
Tags: Javascript Object, Front End Development, Javascript Tips, JavaScript

Is there an alternative (and maybe better way) to determine data type of variables in javascript other than typeof? Turns out there is one.

Recently, I was looking at some code and found a different way some developers were using to determine the data types using Object.prototype.toString instead of typeof. On further exploration, I found that Object.prototype.toString gives much better results as compared to typeof and can be useful at a lot of places.

Let’s look at some of the results it gives:

Application

Though typeof works fine for most of the cases, this function will come in handy covering cases such as

we need to differentiate between various types in objects (such as arrays, null, object, date)

we need to get correct data type for primitive variables created using their respective object wrappers (e.g. new Number(10) is a number but typeof will give object)

Syntax

One can also write a wrapper around it or even modify the function prototype to remove the unnecessary characters in the output and get only datatypes

Pros vs Cons

It seems typeof is more compact than toString in its usage as well as the result it returns but toString is more accurate.

toString gives more accurate data types which are useful when differentiating between various types of objects (arrays, null, objects, dates)

which are useful when differentiating between various types of objects (arrays, null, objects, dates) toString gives more accurate results in cases if someone has used object wrapper for primitive data types such as new Number/String.

in cases if someone has used object wrapper for primitive data types such as new Number/String. toString function can be overriden but typeof can’t which seems the only major drawback.

You can read more about the mechanism and working of the function over here

Overall, Object.prototype.toString is a pretty good method to determine the datatypes correctly in lot of cases.
How to Split a String in JavaScript
By: Javascript Jeep
Tags: Javascript Tips, JavaScript, Web Development, Programming, Coding

Understanding the Split Method in JavaScript

Image taken here.

The split method spilt the string into array of substring based on the pattern provided.

Example

let numbersStr = "1,2,3,4,5"; let numArray = numbersStr.split(","); console.log(numArray); // ["1","2","3","4","5"]

In the above example , the split method will loop through all the character of the string , if the pattern provided is found then the split method will collect the characters looped before finding the pattern and join all the characters as a string and pushed that string into an array .

If we don’t pass any pattern then the entire string will be pushed to an array and returned

numbersStr.split(); // ["1,2,3,4,5"];

If the pattern passed is the first character of the string , then an empty stirng is pushed into the array .

numbersStr.split("1"); // ["", "2,3,4,5"]

Also if the pattern passed is the last character if string , then an empty string is pushed to the resultant array.

numbersStr.split("5")' // ["1,2,3,4", ""]

If we pass pattern as empty string the each character of the string is splitted and pushed into array

numbersStr.split("");

// ["1", ",", "2", ",", "3", ",", "4", ",", "5"]

We can also pass number of split operation to be done by passing the limit param.

numberStr.split(",", 2); // ["1", "2"]

If we pass limit as 0 then an empty string will be returned

numberStr.split(",", 0); // []

Real world Example .

Getting the value from css property in JavaScript .

let divHeight = document.getElementById("div1").style.height; //10px let height = divHeight.split("px"); console.log(height); // "10"

2. Reversing a string

let name = "test"; let splittedArray = name.split(""); // ["t", "e", "s", "t"] splittedArray.reverse(); // ["t", "s", "e", "t"] let reversedString = splittedArray.join(""); // tset

Thank you for reading. If you found this useful, please consider donating to me via PayPal.
Javascript for beginners: clz32 method
By: Tomasz Smykowski
Tags: Javascript Development, Javascript Tips, JavaScript

Founder of Summon The JSON. Armadillo Of Coding. 20y of #Programming 🚩 TOP 2% SO. 1kk Quora #JavaScript #Python #CSharp #PHP #Java
var , let and const in js
Tags: Javascript Development, Javascript Tips, JavaScript

“ Hey peeps let us understand the concepts of var , let and const in js ”

1.) var is function scoped or globally scoped whereas const and let are block scoped let us see an example for this :



function variable(){ var a = “hey guys” // variable a is visible throughout this function if(true){ console.log(a); } function inner(){ console.log(a) } inner(); } variable();

Example for let and const (block scoped)

function letandconst(){ if(true){

// variables a and b are visible only in this block let a = "inside if block";

const b = "inside if block"; console.log(a);

console.log(b); } for(let i=0 ; i<5 ; i++){ // variables a and b are visible only in this block let a = "inside for loop";

const b = "inside for loop"; console.log(a);

console.log(b); } // variables a and b cannot be accessed outside there scope(block) } letandconst();

2.) var is hoisted where as let and const are not hoisted wait what is hoisting , hoisting means accessing a variable even before declaration and yea , only the variable is hoisted the value of variable is not hoisted so we get undefined if we use it before giving it a value but in let and const it will throw an error

console.log(a); // undefined (bcoz only the variable is hoisted the value of it is not hoisted) var a = 10 ; console.log(10); // 10 /*---- let and const are not hoisted ---*/ console.log(b);

console.log(c); let b = 10;

const c = 20; // this piece of code will throw an error

3.) var can be updated or redeclared whereas let can only be updated but can not be redeclared and const can neither be updated nor be redeclared

// in this below code there will be no error as var can be updated and redeclared function forvar(){ var a = 10 ; // declaration console.log(a); a = 20 ; // updating console.log(a); var a = 21; // redeclaration console.log(a) } forvar() // in this below code there will be error as let can only be updated but cannot be redeclared function forlet(){ let a = 10; // no error (declaration) console.log(a); a = 20; // no error (updating) console.log(a); let a = 11; // error (redeclaration) console.log(a); } forlet() // in this below code we will get error as const can neither be updated nor be redeclared function forconst(){ const a = 10; console.log(a); a = 20; // error (const can not be uodated) const a = 11 ; // error (const can not be redecalred) }

4.) var and let can be declared without initialization , const must be initialized during declaration
17 Interesting JavaScript Tricks | Hacker Noon
By: Rizwan Ali
Tags: Front End Development, Javascript Tips, JavaScript, Interesting Javascript, Tricks And Skills

Front-end Web Developer and Blogger

There are many ways to write code but generally the first way for many people is very long and can take you some time. Here is my latest post that will increase your efficiency and productivity when coding JavaScript.

JavaScript: Tricks You Should Know

The ternary operator

Noobs:

Pro:

Number to string / string to number

Noobs:

Pro:

Populating an array

Noobs:

Pro:

Dynamic properties in objects

Noobs:

Pro:

Read more => 3 Steps to learn a programming language

Removing duplicates

Noob:

Pro:

Array to object

Noob:

Pro:

Read more => Complete Guide To Fetch API

Object to Array

Noob:

Pro:

Short circuit conditionals

Noob:

Pro:

Use ^ to check if numbers are not equal

Loop over an object Object keys are stored in insertion order Check if value is an array Initialize an array of size n and fill with default values Truthy and False values

Truthy values => “ Values”, “ 0”, {}(empty object), &[](empty array)

Difference between double equal and triple equal Better way to accept arguments

function downloadData(url, resourceId, searchTest, pageNo, limit) {} downloadData(...); // need to remember the order

Simpler way to do:

null vs undefined

null => It is a value whereas undefined is not.

null is like an empty box and undefined it not box at all.

When null is passed, the default value is not taken. Whereas, when undefined or nothing is passed the default value is taken.

Need help in raising funds to buy a Mechanical Keyboard. This pandemic has affected my family badly so can’t ask my DAD for it.

⚡Thanks For Reading | Happy Coding 🍺

Previously published at Join Hacker Noon https://rahulism.co/2020/11/29/_17-pro-javascript-tricks-you-didnt-know/

Create your free account to unlock your custom reading experience.
Namespace in JavaScript
By: Md Shahab Uddin
Tags: Website Design, Javascript Tips, JavaScript, Web Development, Web Design

Namespace in JavaScript

What is a Namespace and Why we need a Namespace?

Whatever we write in javascript is the properties of the global window object. Sometimes we need to use the same identifier(variable, function) multiple times. But, due to scope problems naming collision occurs.

The namespace provides scopes to identifiers to avoid naming collision between them. We use the same variable in different contexts. Using namespace helps us to use the same variable in different namespaces.

Suppose we want to use two functions with the same name. But doing so creates an error

So, to escape error we will use a namespace through which we can use these two function easily without any error

How do we create a Namespace?

We normally create one global object which contains all variables, functions as properties of the object. It help’s us in a way that it doesn’t pollute the global environment.

Example of Namespace

Look at the code above. We used the eat and sleep function in both men and women object. Here these function doesn’t collapse with one another.

2 eat function + 2 sleep function = 4 functions in total inside two global object. In this way, we can nest hundreds of variables and function inside one global object.

Using namespace we created two sleep functions and they are working without any error.

Keep in mind that these functions aren’t accessible outside of the object. This won’t work.

sleep();

eat();

That is why we can use this namespacing method to hide our code.

There are some other ways to hide code. Let’s look at these methods.

Ways to hide code

1st method: Wrap the code inside curly braces. You must use let/const to declare variables and functions.

2nd method: Wrap with function with “()” and then call the function with “()” at the end.

It doesn’t matter you used const/var/let to declare variables or functions. All variables and functions will be inaccessible from the outside

Thank you so much for reading my article
Nice article.
By: Konstantin Rouda
Tags: Javascript Tips, JavaScript, Javascript Development, HTML, CSS

Nice article.

A little note regarding using a number as an ID. It's not valid because CSS selector cannot start with a digit, two hyphens, or a hyphen followed by a digit.

If you curious enough here are some links from the Documentation

ID Selectors:

https://drafts.csswg.org/selectors-3/#id-selectors

Valid CSS identifiers:

https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
4 ways to check if the property exists in JavaScript Object
By: Sanchitha Sr
Tags: Webdev, Javascript Tips, JavaScript, Javascript Object, Programming

1) Using Object method hasOwnProperty()

The most common solution would be to use hasOwnProperty() which is one of the common object methods. This method returns a boolean indicating whether the object has the specified property.

var favAuthor = {

name: 'Dan Brown',

favBook: 'Lost Symbol',

favCharacter: 'Robert Langdon'

} if(favAuthor.hasOwnProperty('favCharacter')) // true

{console.log('The property exists')} else {

console.log('The property does not exist')

}



If the property does not exist, it will return false

console.log(favAuthor.hasOwnProperty('favVillain')) // false

2) in Operator

The in operator returns true if the specified property is in the specified object.

var favAuthor = {

name: 'Dan Brown',

favBook: 'Lost Symbol',

favCharacter: 'Robert Langdon'

} if('name' in favAuthor) // true

{console.log('The property exists')} else {

console.log('The property does not exist')

}

If the property specified does not exist, the expression will return false

console.log('favVillain' in favAuthor) // false

3) Using typeof and compare it with undefined

If the property doesn’t exist, the type of the property should be ’undefined' and hence we can use typeof operator and comparing it with ’undefined' .

var favAuthor = {

name: 'Dan Brown',

favBook: 'Lost Symbol',

favCharacter: 'Robert Langdon'

} if(typeof favAuthor.name !== 'undefined') // true

{console.log('The property exists')} else {

console.log('The property does not exist')

}

If the property specified does not exist in the mentioned object, it will return false

console.log(typeof favAuthor.favVillain!== 'undefined') // false

4) Using !! operator (double-bang operator)

This is the least known method to check the property in the object. In Javascript, every value has an associated boolean, true or false. For example, a null value has an associated boolean value of false . A string value, such as abc has an associated boolean value of true .

You can find the list of truthy values here and the falsy values here.

Null is a falsy value.

!!null // false

So we can take advantage of that by the name of the property we want to check using the !! operator. If the key to the property value is not null, it will return true

var favAuthor = {

name: 'Dan Brown',

favBook: 'Lost Symbol',

favCharacter: 'Robert Langdon'

} if(!!favAuthor.name) // true

{console.log('The property exists')} else {

console.log('The property does not exist')

}



If the property equals to null, which means the property does not exist, it will equate to false since null is falsy.

console.log(!!favAuthor.favVillain) // false

And that sums it up!

Thanks :)
7 Important Methods For JavaScript Objects
By: Harsh Patel
Tags: Javascript Tips, JavaScript, Frontend Development, Programming, Coding

As you might know that JavaScript objects are a collection of key/value pairs. Values ​​can contain properties and paths and may contain all other JavaScript data types, such as strings, numbers, and Booleans.

All JavaScript entries are retrieved from the parent architect. Object has many useful built-in methods that we can use and achieve to make working with individual objects straightforward. Unlike Array prototype methods such as sort () and reverse () used on the same members, Object methods are used directly in the Object constructor and use an object model as a parameter. This is known as the vertical path.

This article will go through the important built-in methods, each section below works in a specific way and provides an example of implementation.

1. Object.freeze()

As the name suggests it won’t let you add or remove any new property to the object or won’t let you modify the object either.

const gadgets = {name:'macbook', model:'pro', year:2020}

Object.seal(gadgets)



//this won't work

gadgets.year = 2021

console.log(gadgets.year) // output 2020



//this won't work

delete gadgets.year

console.log(gadgets.year) // output 2020
Strict Mode in JavaScript
By: Reina Mitchell
Tags: Programming, Code, Javascript Tips, JavaScript

Strict Mode in JavaScript

Introduction

I have been writing my recent blog posts to reflect the ways in which I am trying to clean up and make my JS code more readable. One of those ways I want to talk about in this blog post is implementing “strict mode” into your code.

Strict mode in JavaScript is a literal expression that you add into your code that lets the compiler know to execute your code in “strict mode”. To use “strict mode”, you can place the expression, “use strict” at the beginning of your code so that it is globally scoped, or you can place it within specific functions or blocks. For simplistic purposes, I like to just put it at the top of my editor in the global scope so that all the code will be in “strict mode” now.

Now you might be asking what would be the purpose of this?

It makes sure that your code is less error-prone. For example, if you try to write a variable without a declaration, it will cause an error:

This is the error message I get back from the console

I think this is an amazing feature from ES5 that is really helpful, especially if you find that you do not have something like ESLint already installed in your editor(if you do, it should still work).

As a result of “strict mode” not allowing for undeclared variables, this also means a by-product is catching misspelled variables.

On line 7 and 8, I misspelled voting and instead wrote votin , but since votin was never declared I automatically get a ReferenceError and it won't run. I will get a message telling me:

If I were to run this code without the ‘use strict’ expression, however, no error would occur:

I simply get back undefined. I could continue writing code and only to later find out that voting actually never gets assigned anything :(

Strict mode helps us avoid an error like this!

Reserved Keywords

I can never remember, with the exception of the more common keywords, which ones are reserved words. Strict mode will tell you if your variable name is a reserved keyword with an error message.

Conclusion

I hope this helps you write cleaner code and if you have any more questions regarding ‘strict mode’, I suggest looking up the documentation on it as it is super helpful as well.
Function Declaration Vs Function Expression in JS
By: Aiman Nazmi
Tags: Javascript Tips, JavaScript, Programming Languages, Programming, Coding

I stumbled upon this question when learning JavaScript the other day, so I did some reading to understand the differences between those two types of function. I will try to summarise few points that I gathered based on my reading.

Intro to Function Declaration

// Example of Function Declaration

function multiplyNum(firstNum, secondNum) {

return firstNum * secondNum;

}

Function declaration declares a function and will be invoked once we call the function. Also, we need to define it using function keyword, followed by name and parentheses {}.

Intro to Function Expression

// Example of Function Expression

var multiplyNum = function(firstNum, secondNum) {

return firstNum * secondNum;

}

Function expression is basically a JavaScript function that is stored in a variable. In the example above, we do not write the function using function keyword first, instead we write it as if we define a variable.

Hoisting

This is subtle yet an important difference between those two functions. When we run the JavaScript file, function declaration will be hoisted to the top of the code before any code is executed. In other words, functions written as function declarations are known before the code is run.

// We can call the function before we declare it

console.log(multiplyNum(1,3))



// Example of Function Declaration

function multiplyNum(firstNum, secondNum) {

return firstNum * secondNum;

}

//3

On the other hand, functions written as function expressions are not hoisted when we run the script. An example is when we run the code below, we will encounter an error instead of the value 3.

// When we call the function before we declare it

console.log(addNum(1,4))



// Example of Function Declaration

var addNum = function(firstNum, secondNum) {

return firstNum + secondNum;

}

// We will get error message instead of the value 5.

Which One Should We Use?

The answer is it is a matter of personal preference. If you want to call a function before we declare it, then obviously function declaration is the best option. If you want to have a better structure, then you might consider function expression as the answer.

All in all, happy coding and I hope that you have learned something from this post. Cheers!
Javascript : Null & Undefind. In this blog, I will try to explain the…
By: Deepak Jha
Tags: Javascript Tips, ES6, JavaScript

In this blog, I will try to explain the difference between these two primitive type variables in javascript, which many people find very confusing.

Basically, they represent nothingness or something not there but there are few differences between them. So both are primitive types and we can print on console and also can define to a variable.

Null

It is a value of the primitive type that is an intentional absence of any value and we have to assign it by ourselves so we can create a variable and set it to null.

Example:

We can have a variable currentUser and we can explicitly set the value of this variable to null if there is no user and we can set the value of this variable when the user logged in and have. By setting the value of this variable to null we are telling javascript that there is value here and this value is of nothing.

Undefined

JavaScript assigns ‘undefined’ to any object that has been declared but not initialized or defined. It is the property of the global object. Usually, we don't set something to be undefined by ourself but technically we can and it creates at runtime. Normally we get back undefined from javascript. Both of them have kind of similar concepts like we can manually or explicitly assign the value of null to a variable.

Example

Array index or object property that does not exist.
Currying in 1min!
By: Jatin Chauhan
Tags: Javascript Tips, JavaScript, Function Currying

Currying in 1min!

Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Jatin Chauhan ·Dec 4, 2020

Currying is a transformation of functions that translates a function from callable a f(a, b, c) into callable a f( a )( b )( c ).
Interview Question — JavaScript Arrays — Find Flight at index
By: Deeksha Sharma
Tags: Javascript Tips, JavaScript

Browser JavaScript and Event Loop Course is available at http://bit.ly/39eDgEA

The code is available at https://bonsaiilabs.com/js-array-interview-flight/

We need to get the output for this piece of code.

There is a JavaScript array called flights containing 6 flights.

Then, we add to flights array on index 8 a new flight “Virgin Australia”

Finally, we want to log the value at index 7 in flights.

So..let’s understand at what happens when we run this code.
The setTimeout and setInterval methods in JavaScript
By: Amitav Mishra
Tags: Javascript Tips, Web, JavaScript, Javascript Development, Web Development

Photo by Veri Ivanova on Unsplash

The setTimeout() method

The setTimeout() method calls a function after a specified time provided in milliseconds. This method takes a function as a first argument and time in milliseconds as the second argument. You can write your logic inside the function body which will execute after the time you have specified.

For example: Show an alert box after 5 seconds.

setTimeout(()=> {

alert('Message after 5 seconds');

}, 5000);

To cancel the timer, you can store the timer first in a variable and call the clearTimeout() function by passing the timer as argument.

var timer = setTimeout(()=> {

alert('Message after 5 seconds');

}, 5000); clearTimeout(timer);

The setInterval() method

The setInterval() method calls a function at specified interval of time provided in milliseconds. It takes function and time (in milliseconds) as its arguments.

For example: Print a random number every second.

setInterval(() => {

console.log(Math.random());

}, 1000);

To cancel the interval, you can store the interval first in a variable and call the clearInterval() function by passing the interval as argument.

var interval = setInterval(() => {

console.log(Math.random());

}, 1000); clearInterval(interval);

Create a running clock timer

To create a running clock, we need to take help of setInterval() method and Date object. We can get the current time by creating a new Date object.

new Date().toLocaleTimeString(); // 6:30:49 PM

Once we create a Date object, it will give us the Date information of current time, it will not change its value with the passing time. So we need to create a fresh new object every time to get the latest date and time.

For this example, we will create a new Date object every second and print that.

var date = setInterval(() => {

console.log(new Date().toLocaleTimeString());

}, 1000);

To show the running clock timer on a web page, you can create a div element in HTML and set the it’s innerHTML with the latest time every second.

HTML

<div id="time"> </div>

JavaScript
Por que você deveria se preocupar com as pesquisas na árvore DOM?
By: Laura Oliveira
Tags: Code, Javascript Tips, JavaScript, Performance, Dom

A young girl that feels extremely facinated in study new things, cultures and worlds. And in her free hours let the imagination play around with the words.
How do you copy by value a composite data type?
By: Namrata Dwivedi
Tags: Javascript Development, Javascript Tips, JavaScript

We use data types to specify what kind of data can be stored & manipulated within a program.

In Javascript, the data types can be classified into 3 major categories as:

Primitive (pass by value) Trivial Composite (pass by reference)

Primitive data types

String, Boolean and Number are primitive data types.

Primitive data type example illustration

From the above code snippet, we infer that “Primitive data types can hold only one value at a time.” In the above example when a is assigned to b, copy of a is created for b and if we are changing the value of a, the value of b is not affected because already another copy of a is created and stored for b.

Composite Data Types (pass by reference)

Objects, Array and Function (which are all types of objects) are composite data types.

Composite data type example

“Composite data types can hold collections of values and more complex entities.” Variables that are assigned a non-primitive value are given a reference to that value. That reference points to the object’s location in memory. The variables don’t actually contain the value.

Trivial Data Types

‘Undefined’ and ‘Null’ are trivial data types.

Trivial data type example

The undefined data type can only have one value-the special value undefined. If a variable has been declared but has not been assigned a value, has the value undefined.

A null value means that there is no value. It is not equivalent to an empty string (“”) or 0, it is simply nothing.

How to Copy by value a composite data type?

Copy by value a composite type can be achieved with the help of spread operator (…).

Copy by value example for Composite Data Type

Spread operator allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

#JavascriptTips #Javascript