Which is the best JavaScript book?

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Watch this JavaScript tutorial for beginners to learn JavaScript programming from scratch. 👍

⭐️Course Contents⭐️

01 | Introduction

Get an introduction from Bob, as he kicks off the course, sets expectations, and gives you a little guidance for the road ahead.

02 | Setting Up the Development Environment

See how to install Node and Visual Studio Code, and learn why you need each. Watch as Bob writes a first tiny line of code to make sure that the installation is ready.

03 | Basic JavaScript Syntax

Hear about the basics of the JavaScript syntax, including how JavaScript is executed, how to create a properly formed statement, and more.

04 | Variables

Learn what variables are and how to declare, initialize, set, and get values from them.

05 | Data Types

JavaScript works with data types differently than other programming languages do. Learn from Bob as he explains some of the most basic data types and how to determine the type held by a variable.

06 | Type Coercion and Conversion

Sometimes you need to explicitly convert the data type of a value into a different data type. Sometimes JavaScript will do this automatically for you. Bob explains how and why this happens.

07 | Expressions and Operators

Learn how to spot a well-formed expression and how to compose expressions through the combination of operators and operands.

08 | Arrays

Watch as Bob demonstrates how to use arrays, how to add/remove elements of an array, how to access elements of an array using the index, how to get the number of elements in an array, and more.

09 | Function Declaration

Get an introduction to functions, as Bob shows you one way to define a function, how to call the function, how to pass parameters into a function, how to return values from a function, and more.

10 | Function Expressions

Sometimes a function declaration is more than you need. Get details in this lesson, as Bob demonstrates how to use a function expression and how to create an immediately invoked function expression.

11 | Decision Statements

Learn how to add logic to your applications by testing conditions using if / else statements, switch / case statements, and the ternary operator.

12 | Iteration Statements

Watch as Bob introduces the For and While statements, which enable you to loop through lists of values and perform operations on them.

13 | Basics of Scope

Hear an explanation of the notion of the lifetime of variables and their reach into other code blocks, in this discussion of scope.

14 | Returning Functions from Functions

As a building block toward a more sophisticated approach to building JavaScript applications, see how you can return functions from functions.

15 | Object Literals

Objects contain properties and functions that describe attributes of the object and its behavior, respectively. Watch as Bob demonstrates how to create object literals.

16 | Module Pattern and Revealing Module Pattern

Learn how to introduce variables and functions without leaving an unnecessarily large footprint on the global scope.

17 | Closures

Closures allow developers to bind functions to their execution context, including variables, so you can build specialized versions of functions. Learn how closures work and how to create them.

18 | this Keyword

Get the details on the "this" keyword, which causes a lot of confusion for JavaScript developers. Listen as Bob explains what this mysterious object is and how to bend it to your will.

19 | Destructuring

See how to use destructuring, a new feature in JavaScript that allows you to unpack array elements or object properties in a concise syntax.

20 | String Template Literals

Learn about the new string template literal syntax to enable string interpolation, multi-line string formatting, and more.

21 | Regular Expressions

Working with string data, Bob explains how use regular expressions to determine such things as whether a string matches a specific pattern or whether an instance of the pattern exists in a string.

22 | Built-In Natives

Join Bob as he examines native, built-in JavaScript functions that return objects that box the primitive types in order to provide additional helper methods on your values.

23 | Constructor Function Calls with the new Keyword

Learn how constructor functions work, see how to make key distinctions in what they are, and find out why they’re helpful.

24 | Objects and the Prototype Chain

Moving past the absolute beginner matter, listen in as Bob explains how objects work in JavaScript and how you can create an object that is linked to another object.

25 | JavaScript Classes

Bob demonstrates how “syntactic sugar” works on top of the existing functions and prototype chaining to help JavaScript resemble more traditional object-oriented programming languages.

26 | Arrow Functions

The latest version of JavaScript added arrow functions, a shorthand syntax for creating functions. Watch as Bob demonstrates how to create them and shows where they’re useful.

27 | Truthy and Falsy Values

Listen is as Bob circles back to topics that are important (but didn’t easily fit into earlier topics) and looks at the odd way in which JavaScript evaluates certain expressions as truthy and falsy.

28 | null Type

Similar to the undefined primitive type, the null type represents a variable that has no reference to an object when one was expected. Hear an explanation of how and why we should think about nulls.

29 | Date Objects

No discussion of JavaScript would be complete without understanding the Date built-in native function which provides properties and methods for working with dates and times.

30 | String Methods

The built-in native String function provides several very useful methods for manipulating and evaluating strings. Watch Bob demonstrate how to use a few of the most useful ones.

31 | Array Methods

We’ve worked with arrays throughout this course. Now Bob takes a few minutes to show you some of the most useful methods provided by the Array built-in native function.

32 | Error Handling with Try Catch

See how to wrap a try/catch/finally statement around potentially problematic code to anticipate everything that could go wrong with it, and learn other error-handling tips.

33 | Understanding the Document Object Model

Watch Bob examine the web browser environment and how it creates an object graph of nodes that represent elements, their attributes, and text, plus how to properly attach your code to an HTML page.

34 | Working with DOM Nodes

Continuing from the previous video, Bob demonstrates a slightly more compelling example that helps us understand how to manipulate, create, and delete element nodes and attribute nodes.

35 | Course Conclusion

In this final video, Bob briefly adds some closing comments and well wishes. You can also optionally complete a survey to provide insight into how Microsoft can improve this course.

Thanks for watching

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

20 Things to Learn and Effective tips to becoming JavaScript Master

20 Things to Learn and Effective tips to becoming JavaScript Master

Do you want to get into web development? Or perhaps you’re fascinated with code and software? If so then JavaScript is a good choice for you. In this post, we will for you 20 things to learn and Simple Effective tips on the way to becoming a JavaScript Master

10 THINGS TO LEARN

I guess you are a web developer. Hopefully you are doing fine and you have a great job, maybe you are even self-employed or working as a freelancer. Maybe you are just starting out as a web developer, maybe you have been working as a programmer for a longer period already.

However comfortable you are with JavaScript, it is always good to get a refresher on some topics to read up about or get them on the radar in the first place. Here are 10 things you definitely have to learn before you can call yourself a master in JavaScript.

1. Control Flow

Probably the most basic topic on the list. One of the most important, maybe the most important one. If you do not know how to proceed with your code, you will have a hard time. Knowing the ins and outs of basic control flow is definitely a must.

  • if else — If you don’t know these, how did you write code before?
  • switch — is basically if else in a more eloquent way, use it as soon as you have multiple of different cases.
  • for — Do not repeat yourself, this is what loops are for. Besides the normalfor -loop for of and for in come in very handy. The big advantage of for -loops is that they are blocking, so you can use async await in them.
  • Advanced conditionals — Using the ternary and logical operators can make your life a lot easier, especially when you try to do things inline, meaning that you don’t want to save values to use them later. Example:
// ternary
console.log(new Date().getHours() < 12 ? 'Good Morning!' : 'Time for a siesta')
// logical operators
const isJsMaster = prompt('Are you a JavaScript master?') === 'true'
console.log(isJsMaster && 'proficient coder')

2. Frontend Framework

The big three are React.js, Angular and Vue.js. If you are looking for a job nowadays, you will almost always have one of those listed as a prerequisite. Even if they change quite quickly, it is important to grasp the general concept of those to understand how applications work. Also, it is just easier to write apps that way. If you haven’t decided which train you want to jump on, my suggestions is React.js. I have been working with it for the last couple of years and did not regret my decision.

3. Asynchronity

This is a very important aspect of JavaScript, Either you are fetching data from the backend or you are processing requests asynchronously in the backend itself. In pretty much all usecases, you will encounter asynchronity and its caveats. If you have no idea what that is, you will probably get a weird error, which you will try to fix for a couple of hours. If you know what it is, but you don’t really know what to do about it, you will end up in callback-hell. The better approach is to use promises and/or async await in your apps.

4. Node.js / Express

Even as a frontend developer, you should know the basics of node.js. Ideally, you would also know how to spin up a simple express server and add some routes or change existing ones. JavaScript is great for writing scripts to help you automate a lot of tasks. Therefore, knowing how to read files, work with filepaths or buffers gives you a good toolset to build anything.

You may also like: Best Design Patterns for writing JavaScript Web applications

5. Error handling

This took a while for me. It does not matter if you are working on frontend or backend, the first year or so, you will probably default to console.log or maybe console.error for ‘handling’ errors. To write good applications, you definitely have to change that and replace your lazy logs with nicely handled errors. You may want to check out how to build your own Error constructor and how to catch them correctly, as well as showing the user what the actual problem is.

6. Data Models

Similar to moving through your application continuously, you have to decide where to group specific information chunks and where to keep them separate. This does not only apply to building database models, but also function parameters and objects or variables. Example:

const calcShape = (width, height, depth, color, angle) => {...}
const calcShape = ({width, height, depth, color, angle}) => {...}

7. DOM Manipulation

This is an interesting topic. Normally it is somewhat left out in the day today life as a developer. Maybe you learned jQuery and never felt the need to pick up some native DOM manipulation skills, maybe you are just using a frontend framework, where there is rarely a need for custom DOM manipulation. However, I think this is a crucial part of understanding JavaScript, at least in the frontend. Knowing how the DOM works and how to access elements gives you a deep understanding of how websites work. In addition, there will be the point where you have to do some custom DOM manipulation, even when you use modern frontend frameworks, and you definitely do not want to put jQuery in your package.json just to access an element.

8. Functional Approach

There is an everlasting debate about functional vs. object-oriented programming. You probably can achieve the same thing with both of the approaches. In JavaScript, it is even easier, you have both of the approaches available. Libraries like lodash give you a really nice collection of tools for building applications with a functional approach. Nowadays, it is not even necessary to use external libraries any more. A lot of the most important functions have been implemented in the official JavaScript specification. You definitely should know how to use map reduce filter forEach and find.

9. Object Oriented Approach

Similar to the functional approach, you also have to get familiar with object oriented JavaScript, if you want to master it. I neglected that part for a long time in my career and just worked my way through with a workaround, but sometimes it is definitely better to use objects/classes and instances to implement specific functionality. Classes are widely used in React, MobX or custom constructors.

10. Bundling / Transpilation

Unfortunately, this is a big part of web development. On the one hand I should not say unfortunate, because it is great to be able to write code with all the newest features. On the other hand, the reason why I’m saying that is that we always have to keep in mind that there’s older browsers around that may not support these features, therefore we have to transpile our code into something else that the old browsers understand. If you work with node.js, you will probably have less exposure to transpiling your code. The de-facto standard for transpilation is babel.js, so get familiar with it. As for bundling your code and tying everything together, you have a couple of options. Webpack was the dominant player for a long time. Some time ago, parcel popped up out of nowhere and is now my preferred solution, since it is so performant and easy to configure, although not perfect.

This is not specific to JavaScript, but incredibly helpful in a lot of use cases. Just as confusing as well. Getting to know the syntax of Regular Expressions definitely takes some time and remembering all of the different options is impossible.

10 SIMPLE and EFECTIVE TIPS

Do you want to get into web development? Or perhaps you’re fascinated with code and software? If so then JavaScript is a good choice for you.

Why JavaScript?

Javascript is the scripting language of the internet and one of the most essential web technologies along with HTML and CSS. It’s a high-level, interpreted programming language that conforms to the ECMAScript specification. In more simplistic terms, it’s what allows you to implement and display complex things on your webpage, to create content, to animate images and tons of other amazing possibilities with just a few lines of code.

There’re plenty of reasons to learn this wonderful programming language. The most important one is the fact that JavaScript runs everything and everywhere. Most of the prominent websites are built on the backbone of JavaScript while currently there are more than 3 billion devices be it Smartphones or desktops. JavaScript went through a massive surge of popularity and quickly become the most dominant language in the world of software. In light of this, it’s obvious that Javascript skills are in high demand by companies everywhere. For all these reasons and more, it’s lucrative to have JavaScript skills on your resume.

Why is it challenging?

Learning JavaScript is easier said than done. Newcomers often run into similar kinds of problems such as difficulties in understanding confusing concepts. Not only that, but JavaScript also has an ever-changing tooling landscape one that makes it even far more grueling to understand. It’s hard to find the motivation to complete a demanding task such as this. JavaScript is also a vigorously un-typed language which means that the same thing in one code can easily mean something different depending on the context and medium. It also is extremely hard to debug due to a non-existent support system for different classes.

Tips for JavaScript Beginner

So the question is how to learn JavaScript? Similar to every complicated thing in life, you can learn JavaScript coding through constant practice and by never giving up. To help you in this task, we have written down the best way of learning this skill just for you! Try to follow these tips to enhance your learning experience.

1. Keep experimenting & Interact with veterans

Find and make your own way to solve problems related to JavaScript. Keep experimenting with the problems and what you have learned so far. Also, do interact with the veterans as the large community lead to more support and help you’ll be able to receive. Fortunately, JavaScript has one of the largest internet communities that is all about giving and receiving help and exploring the world of JavaScript. Take advantage of that! Meet up with the experts to not only motivate yourself to study but to learn as well. You might even be offered a mentorship! By being a part of a community, you’ll also be able to keep up to date with new, innovative tools!

2. Do not rush! Go step by step

I know it’s tempting to move on immediately once you understand a concept, but don’t! Instead, play with what you have learned, get comfortable and even combine it with the previous lessons. Start from beginner’s level and cover all the topics from tutorials, check resources, implement what you have learned and when you are finally confident of your beginner level skills, then move on to the intermediate level and after that, to advance level. By limiting the learning content and keeping in touch with the previous lessons, you’ll be able to retain the material in your head and find it easier to remember key concepts. The process seems long for sure but it actually takes far less time since you don’t have to keep revising and is actually quite fun. There’s really nothing that you cannot do with JavaScript in regards to web development.

3. Look out for JavaScript Resources

The internet has millions of sources available for you to use. Take “JavaScript: The Definitive Guide” by David Flanagan. It’s a book that has been forever considered a bible for JavaScript programmers across the world. In it is a comprehensive guide that is well-organized and detailed for new programmers to learn and old programmers to revise. Another book that you can read is “You Don’t Know JS: Up and Going” by Kyle Simpson which provides the necessary background for those with limited knowledge about programming. The entire series introduces more complex and harder parts of the JavaScript language as you read on one book at a time. Furthermore, there are tons of articles, blog posts and even YouTube videos available for reference. Don’t waste these valuable resources!

You may also like: Keeping your JavaScript code clean forever and scalable

4. Right attitude

The first thing you need to do is to go with the right attitude to learn JavaScript. Learning JavaScript is going to become needlessly more bothersome if you approach it with the wrong mindset. Trying to learn it with an “I need to get this over” mindset is not going to take you anywhere. It’s a huge struggle to face and you truly have to be passionate about code to learn it. Not only that, you need to remind yourself to have fun with what you’re learning as JavaScript code is capable of astonishing things once you get the hang of it.

5. Start Slowly

A mistake many beginners make is that they directly start working on frameworks such as jQuery, AngularJS, Backbone, etc. You should never do it. Instead, you should start working on DataTypes and in-built methods. After getting enough of the fundamentals, you can try NodeJS. Trust me, NodeJS is very simple, just a JavaScript code backed up with inbuilt libraries. Then, you can try frameworks.

6. Find the perfect editor for JavaScript

You can’t code without a text editor. Fortunately, you have tons of options to choose from. To write JavaScript code, you can either use your Windows notepad or even download programs such as Notepad++ or Visual Studio Code. Either way, after going through all possible editors, choose the one that you’re most comfortable to work on as this is where you’ll be spending most of your time. Also when you’re starting out, it’s essential to choose an editor that has a simplistic interface and will support you as a beginner.

7. JavaScript Tutorials!

If you search the web for JavaScript tutorials, there are a vast number of tutorials available online on sites such as CodeAcademy, FreeCodeCamp, etc. If you’re a beginner then you should start from beginner level JavaScript tutorials and then move on to intermediate and advanced level. Tutorials are like doing grammar exercises and the sites with JavaScript tutorials are ideal for learning the basics and getting used to the syntax. Learning JavaScript is no different than learning French or Spanish. It takes time.

8. Start Ajax and Async after getting a hang of the basics

After you have spent quite a lot of time on JavaScript, start working on Ajax and Async concepts. Learn how to use different functions on JavaScript and use classes as well. All of these things take quite a lot of time to master but trust me; all your hard work will surely be rewarded.

9. Challenge yourself! Explore JavaScript and learn

When it comes to learning JavaScript, there is always something you can learn as it is a never-ending process. A lot of people end up never improving their JavaScript coding by spending too much time only doing what they are confident about. Make sure that you’re not one of them. Every time you finish a lesson, ask yourself if you have learned something you didn’t know before. That is the key to success. Be mindful of what you want to learn or improve your knowledge of. Make sure that you’re challenging yourself and growing as a developer instead of conforming to a single comfort zone.

10. Keep yourself up to date and be prepared

JavaScript isn’t an easy skill to learn. If it was, it wouldn’t be held with the same reverence as it is in the labor market now. You need to understand the fact that learning JavaScript would require a huge amount of time and dedication. It’s not going to be an easy road. Not only is JavaScript already a complex and intricate skill to master, but it is also a growing field which would require you to stay updated with the new web development practices. Prepare yourself that it’s going to consume a majority of your time. Be patient too. You’re not going to learn JavaScript in a month and maybe not even in a year. All the time spent is going to be grilling, demanding but remember that it will also be completely worth the trouble.

BONUS

Learning JavaScript is constant work and quite difficult but with the right attitude and determination, learning it can be an extremely satisfying experience. All you need is passion and a hunger to learn. Hopefully, with the above-mentioned tips, as well as the other brilliant and detailed materials available online, you’ll be able to grasp JavaScript as quickly as possible while also having a great enjoyable ride.

Hopefully you know all of the topics listed above already. If not, put in the work and try to become a master in JavaScript! It is definitely worth it. Remember that practicing is everything when it comes to coding, so even if you are not familiar with these concepts or know them but you don’t really know how to apply them, it will come in the future.

What do you think about the list? Is something missing? Do you think other topics are more important when coding? Let me know in the comments!

Thank for visiting and reading this post! I'm highly appreciate your actions! Please share if you liked it!

15 Common Mistakes Developers Made While writing JavaScript Apps

15 Common Mistakes Developers Made While writing JavaScript Apps

Every developer make mistake some time when writing apps. This is a normal part of the development process. In this post, we'll learn 15 Common Mistakes Developers Made While Writing JavaScript Apps hope this post will help you

Common Mistakes Developers Made While Writing JavaScript Apps

Every developer make mistake some time when writing apps. This is a normal part of the development process. There are some mistakes that are made more often than others. It is good to be aware of them so that they can be corrected before it’s made. Once we can do that then we can develop apps a lot easier and become a proficient JavaScript developer since we can develop apps that makes less bugs. We will go through some of the more common bugs that are made so we can avoid them here

1. Confusing the Equals

In JavaScript, single equal, double equal, and tripe equal all have their own meanings. Single equal sign is the assignment operator which assigns the value on the left to the variable to the right. Double equal sign is the equality check operator which checks an object’s content for equality without checking its type. The triple equals operator checks an object’s content and the type for equality.

We use the single equal assignment operator like the following:

let a = 1

This is used for setting variable values, so it’s we use single equal in a place that shouldn’t be used like in:

if (a = 1){ ... }

then we would be assigning 1 to a which is always true . This means that the code inside the if statement always runs. That’s definitely not what we want.

Double equal sign shouldn’t be too too much since it doesn’t check the type of the object when checking for equality, so something like:

1 == '1'

if true . This creates problems because if we are only checking for number 1 and we get string with 1 in it, it’s still true. We want to convert them to the same type and then compare them with === to check for equality to avoid ambiguity. So if we want to compare if all forms of 1 are equal to each other we convert them to number first by using:

Number(1) === Number('1')

1 wouldn’t be equal to '1' is we use === since they are different types. This would make things a lot more clear. If we want to make sure something aren’t equal to each other then we can use !== to check if they don’t have the same content or the same type, so:

1 !== '1'

would be true .

2. Mismatching Brackets

Nested statements and functions in each other means that there’re multiple levels of brackets in each file. Usually, apps are pretty complex so the levels can add up. This means that mismatching brackets is easy if you use a text editor that doesn’t support syntax highlight or check for mismatched brackets. This can easily be avoided with modern text editors such as Visual Studio Code, Atom, and Sublime. If we want to use simpler text editors, then use linters and code formatting tools like ESLint and Prettier to detect these issues. They also let us format code automatically and detect common style issues that may occur like quote style inconsistencies, number of characters in a line, functions that can be shortened, etc.

3. Mismatching Quotes

JavaScript lets us use single quotes, double quotes, and backticks for strings. They are equivalent. However, we should open and close with the same character. So if we open a string with single quote then use single quote to close a string, and if we started with double quotes or backticks, then use those to close the string respectively. Also, special characters like quotation marks have to escape to be included in a string in some cases. If you open a string with single quotes, then if you use single quotes in a string, then you have to escape that to include it in the string. This also applies to double quotes and backticks. If you use double quotes in a double quoted string then you have to escape it. And if you use a backtick in a template string, then you have to escape the backtick character.

4. Parentheses

In if statements, parentheses always have to wrap around the whole condition. For example, something like:

if (x > y) && (y < 10) {...}

won’t work. The correct way to write that statement is to write is:

if ((x > y) && (y < 10)) {...}

if we want to check that both conditions are true.

5. Semicolon

Semicolons are optional at the end of a JavaScript line. However, to make things clear for other people, we should include it so that people know where a line ends. We can use a code linter or formatter like ESLint or Prettier to do this automatically. Lots of text editors also have add-ons to fix it automatically for you.

6. Capitalization

JavaScript code is case-sensitive, so things that have different capitalization will be considered different even if they have the same spelling. Anything that references them also have to be capitalized correctly. For example, getElementsByTagName should always be spelled this way with exact same capitalization. The general convention in JavaScript is that we spell variables and function names with camel case, so we should stick with that for consistency if we define our own variables.

7. Referencing Code That’s not Yet Loaded

It’s important that we reference code that have been defined and loaded before hand in order to use the code. If we are using script tag then before we reference the code, we have to load the code first. So the script tag that references the script with the variable we want to use should come before the script tag that references the script that has the code that we want to reference.

Fortunately, JavaScript modules are much more common nowadays, so that we just have to remember to export the code that you want to use in another module and the import the exported variable in the module that you want to use the variable before referencing it. JavaScript modules solves a lot problems with script tags. Global variables do not have to used much anymore to let different scripts reference the same variable, and also we can make variables private without the use of closures since we only need to export the ones that are needed elsewhere.

8. Variable Names

In JavaScript, there are many reserved words that cannot be used as variable names. They shouldn’t be used as variable names since they collide the name of the reserved words, creating confusion with the JavaScript interpreter. To avoid this we should use names that are descriptive like firstName , lastName , and things like that.

9. Scope

We shouldn’t use global variables whenever possible. This means that all variables we declare should use the let or const keywords for variables and constants respectively. This avoids issues with global variable scope and overwriting global variable data. It also let us avoid errors from assigning to entities that should be constant or assigning things accidentally that are global.

10. Missing or Unexpected Parameters

When functions are called with expected parameters missing, then unexpected results may be returned because you passed in unexpected input to a function.We have to make sure that we pass in the right parameters to a function so that we get the right results. It also a good idea to check for unexpected parameters if the function is used in lots of places like functions that are in libraries so that we can deal with unexpected parameters gracefully like ending the execution of the function when parameters passed in are of an invalid type or null or undefined .

11. Index Errors

JavaScript arrays starts with index 0, so the last index of an array will always be 1 less than the length of the array. When you pass in an index that is beyond the length or it’s invalid like a negative number, we get undefined , so we will get ReferenceErrors if we try to get the invalid entry and do stuff with it.

12. Null and Undefined

null and undefined are things that are often the values of variables. This means that we have to check for these when we are getting something by traversing the nested properties of objects or looping through an array. When we have null or undefined we want to handle them gracefully. This means that we should always check for them. So we if have an object called foo and we want to access deeply nested properties within it, then we should check for null or undefined in each level, like so:

if (foo && foo.bar && foo.bar.baz){ ... }

This way we know that all the properties are defined so that we can get access the baz property. For arrays if we want to access index i , we should check if it’s defined by writing:

if (arr[i]){...}

so that we won’t get unexpected undefined errors.

The optional chaining operator (?. ) is being worked on, so hopefully it will be finalized soon and we can use it to access deeply nested properties in an object and we don’t have to deal with properties being undefined as much anymore. Also, Lodash has a get function, which can try to access deeply properties of arrays and objects and get the value if it exists or return null if there’s anything undefined in the middle of the object’s hierarchy. This is much better than a long chain of undefined or null checks.

13. Confusing Undefined and Null

JavaScript has both undefined and null for non-values. However, there are quite a few differences between the two. undefined means that the variable may have been declared, but nothing is set to it. A variable can also be explicitly set as undefined . The type of an undefined variable, when checking the type with the typeof operator, will get us the type 'undefined'. Functions that don’t return anything returns undefined. On the other hand, null values have to be explicitly set by functions that return null or just set directly to a variable. When we check an object that has the null value set, we’ll find that the type of it is'object' if a variable has the null value.

For this reason, it’s probably easier to stick to undefined whenever we can when we’re setting variable values to non-values. It reduces confusion and we only have to check that the type of a variable is 'undefined' to see whether it’s undefined. That’s less painful than having two checks, for both null and undefined.

To write functions that return undefined, we don’t have to do anything like the following example:

const f = () => {}

To set a variable that was assigned some other value to undefined, we can write:

x = undefined;

To check if a property value is undefine, we can write:

typeof obj.prop === 'undefined'

or

obj.prop === undefined

To check if a variable is undefined, we can write the following code:

typeof x === 'undefined'

A declared variable that hasn’t been assigned anything automatically has the value undefined.

If we have to check for null, then we can write:

obj.prop === null

or

x === null

for variables. We can’t use the typeof operator for checking null because the data type of null is 'object'.

14. Confusing Addition and Concatenation

In JavaScript, the + operator is used for both adding two numbers and concatenating strings together. Because JavaScript is a dynamic language, the operands are all automatically converted to the same type before the operation is applied. For example, if we have:

let x = 1 + 1;

then we get two because they’re both numbers. The + operation was used for addition like we expected. However, if we have the following expression:

let x = 1 + '1';

then we get '11' because the first operand was coerced into a string before the + operation is applied. The + operation was used for concatenation instead of addition. When we use the + operator on multiple variables, this makes knowing the type even harder. For example, if we have:

let x = 1;
let y = 2;
let z = x + y;

as we expect, we get three because x and y are both numbers. On the other hand, if we have:

let x = 1;
let y = '2';
let z = x + y;

then we get '12' because y is a string, so the + operator was used for concatenation instead. To solve this issue, we should convert all the operands to numbers first before using them with the + operator. For example, we should rewrite the above example into the following:

let x = 1;
let y = '2';
let z = Number(x) + Number(y);

The code above will get us 3 as the value of z since we converted them both to numbers with the Number factory function first. The Number function takes in any object and returns a number if it can be parsed into a number, or NaN otherwise. An alternative way to do this is to use the new Number(...).valueOf() function, as we do in the following code:

let x = 1;
let y = '2';
let z = new Number(x).valueOf() + new Number(y).valueOf();

Since new Number(...) is a constructor that creates an object type, we want to use the valueOf function to convert it back to a primitive type to make sure that what we get is a number type. A shorter way to do this is to write:

let x = 1;
let y = '2';
let z = +x + +y;

The + sign in front of a single operand will try to convert the single operand into a number or toNaN if it can’t be converted into a number. It does the same thing as the Number function. We can also convert a variable to a particular type of number. The Number object has a parseInt function to convert an object into an integer and a parseFloat function to convert an object into a floating-point number. parseInt takes the object you want to convert to a number as the first argument. It also takes a radix as an optional second argument, which is the base of the mathematical numeral systems. If the string starts with 0x, then the radix will be set to 16. If the string starts with anything else, then the radix will be set to 10.

We can use them as in the following examples:

let x = 1;
let y = '2';
let z = Number.parseInt(x) + Number.parseInt(y)

Also, we can use the parseFloat function as in the following code:

let x = 1;
let y = '2';
let z = Number.parseFloat(x) + Number.parseFloat(y)

We will get 3 in both of the examples above.

15. Breaking Return Statements Into Multiple Lines

JavaScript closes a statement at the end, so one line code is considered distinct from the other. For example, if we have:

const add = (a, b) => {
  return
  a + b;
}

we get undefined if we run console.log(add(1, 2)); since we ran the return statement, which ended the function execution, before a + b is run. Therefore, a + b will never be run in this function. To fix this, we either have to put the return statement all in one line or use parentheses to surround what we want to return. For example, we can write:

const add = (a, b) => {
  return a + b;
}

This will log 3 if we run console.log(add(1, 2)); since we are actually returning the computed result in the function. We can also write:

const add = (a, b) => {
  return (
    a + b
  );
}

This is handy for returning expressions that might be longer than one line. This will also log 3 if we run console.log(add(1, 2));. For arrow functions, we can also write:

const add = (a, b) => a + b

for single-line functions since the return statement is implicit for single-line arrow functions. We can also write:

const add = (a, b) => (a + b)

to get the same thing. This also works for single-line arrow functions.

In JavaScript, if a statement is incomplete, like the first line of:

const power = (a) => {
  const
    power = 10;
  return a ** 10;
}

inside the function then the JavaScript interpreter will run the first line together with the second line to get the full statement. So:

const
  power = 10;

is the same as:

const power = 10;

However, for complete statements like return statements, the JavaScript interpreter will treat them as separate lines. So:

return 
  a ** 10;

is not the same as:

return a ** 10;

Even though JavaScript is a friendly language, it’s still very easy to make mistakes when writing JavaScript code. It’s easy to confuse undefined and null when we aren’t familiar with JavaScript. Because of the dynamic typing nature of JavaScript, operators like the + operator that can do multiple things can easily be converted to a type we don’t expect and produce the wrong result. Also, if statements can be complete on their own, then they shouldn’t be written in their own lines if we want both lines to be together.

Yes, that is all. I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others. Thank you !