The things that every JavaScript developer should know

Source: Internet
Author: User
Tags pear tag name hasownproperty

The things that every JavaScript developer should know2015-06-07 front-end Daquan

(Click the blue Word above to quickly follow us)

JavaScript is a growing language, especially now that the ECMAScript specification is published on an annual release schedule. With the scale and rapid development of this language, it becomes more important to master JS (not just jquery).

This is not a self-proclaimed JS developer knowledge of the Holy Grail of the authoritative guide. But there are definitely some I have missed, some I may be wrong, there are some you may disagree with what every JS developer should know.

How to Fizzbuzz

Translator Note: Fizzbuzz is a British school often play games, from 1 to 100, if you meet a multiple of 3 to say fizz,5 multiples to say buzz, if that is 3 multiples is 5 multiples to say fizzbuzz.

(Fizzbuzz testing) is often considered a good coding exercise to eliminate inexperienced developers during the initial interview process, and you will be surprised to find that many JavaScript developers do not know how to write a basic fizzbuzz test.

The Fizzbuzz test has no practical use. It is purely a simple exercise to test the candidate's potential coding abilities.

Remember that most of the companies that you will be interviewing for front-end or JavaScript development positions will most likely ask you a fizzbuzz question: Are you ready?

This is the classic Fizzbuzz:

Remember that you may be asked to solve different variants of fizzbuzz. I went to the interview once, was asked to solve the basic variant, and then the other two variants.

This particular example outputs "Fizz" in multiples of 3. In multiples of 5 output "Buzz", the imminent is a multiple of 3 is also 5 multiples output "Fizzbuzz".

Note: This implementation has been slightly altered in the early days. Use the conditional if statement, if it is not a multiple of a condition, the number is printed out. Existing solutions can work, but do not print numbers that do not meet the criteria or use the condition if.

for (var i = 1; i <=; i++) {

if (i% 15 = = = 0) {

Console.log (' Fizzbuzz ');

} else if (i% 3 = = 0) {

Console.log (' Fizz ');

} else if (i% 5 = = 0) {

Console.log (' Buzz ');

} else {

Console.log (i);

}

}

The difference between = = and = = =

Two comparison operators you may be familiar with. However, do you know the difference between the double and triple equals comparison operators? Javascript Linter tells you to use triple equals, but do you know why?

= = Double equals (aka Pine equals) does not compare the type, it converts the value in the statement. This is called coercion type conversion, which is considered a harmful operation.

Console.log (24 = = ' 24 ');

True

As you can see, 24 with a single quote is a string that will be converted to a number. While this may be the behavior we expect in some cases, allowing the comparison operator to change the type may not be what you want to do.

It is not recommended to use double equals, the most sensible JavaScript linter will throw an error by default to tell you to replace it with a strict equality comparison operator. If you want to force a value to be converted, do it outside of the condition instead of inside.

= = = Triple equals (aka Strictly equal) compares types, but does not do type conversions, meaning they are compared without being converted. Because there is no forced type conversion, Triple equals faster and is used as a recommended method to compare various values. This means that if the condition equals true, both types need to be the same.

As in the example above, but triple equals:

Console.log (24 = = = ' 24 ');

False

The reason to return false is because we compare a string to a number. Obviously they are two different types, so it will return false.

I strongly recommend that you read more about the equals comparer on the Mozilla developer site. It has some great explanations (better than I explained), and there are some examples.

How to query the DOM without using a third-party library

You might know how to use jquery to query the DOM, but can you use JavaScript native methods instead of using third-party libraries?

I'm not just talking about being able to query page elements by ID or with a specific class element, I mean jquery tends to use expressions to find elements in the DOM.

There are quite a few native methods that we can use, and they are as powerful as jquery to find one or more elements on a page. We can use selectors such as first-child,last-child and so on. You would be surprised to have such a good native Dom query method.

Learn these native methods and use them in places like jquery:

I link the Mozilla developer documentation for further reading when necessary. Anywhere you see a link, if it's something you're not too familiar with, I strongly recommend that you click on it.

    • document.getelementbyid--A classic query that finds elements by ID.

    • document.getelementsbyclassname--finds elements in the DOM through classname.

    • document.queryselector--This is a good way to do it. It has all the power of jquery $ () and it is native. It will return only the first element it finds.

    • document.queryselectorall--is almost the same as the above method, except that it returns multiple elements, not just the first one.

    • document.getelementsbytagname--This allows you to query for elements of a specific tag name. Do you want to find all the DIV elements in the page or Span tab? That's the way you want it.

It is worth mentioning that the Queryselector and Queryselectorall methods can also be used on an element, meaning that you can use these methods to query the contents of an element.

Read more about the use examples of element.queryselector and Element.queryselectorall.

Variable Promotion

JavaScript is an interesting language, and the declaration of a variable will elevate the declaration to the top of the scope. This means that you can refer to a variable before defining it in the current scope, such as when a function is considered to be its own scope.

As a rule of thumb: Always define your variables at the top of the scopes you need. If you are using ' use strict ' at the top of a script file (or in a function), you will throw an error if you use it before a variable is defined.

Most javascript linter such as Jshint, when you are not using the ' use strict ' definition, prompts you to apply best practices so that you cannot use it until the variable is defined.

As always, Mozilla developer documentation has some very good JavaScript articles on syntax and types, and here's an article on variable promotion.

How to use the browser's developer tools

More specifically how to debug JavaScript, but also note the other tools you use in the developer tools. How to set breakpoints and step into code for a specific subset of applications.

These tools are important because they track the running steps of potentially complex applications and find out what causes a problem or a specific bottleneck. Learn how to set a breakpoint, how to really drill down into your code at the molecular level (thin layer) and see what happens.

Understanding the tools bundled in Chrome, Firefox, and later versions of Internet Explorer is an essential skill, especially if you find yourself using JavaScript extensively. Also note the various development tool plugins, such as the Batarang extension on Google Chrome, which allows you to debug ANGULARJS applications.

Use the right tools to find practical problems, and don't blindly optimize your code before this. It is a waste of time to solve problems before they are clear, known as premature optimization.

Console commands

In addition to knowing how to use the analysis and debugging tools in Chrome, Firefox, or Internet Explorer development tools, you should also be aware of the various console commands.

You probably already know Console.log, and Console.error. But there are actually a lot of console commands that can be used.

Keep in mind that some commands may not work correctly under different browsers. I keep an eye on the list of commands that should be well supported by modern browsers, but you'll have to try it before you add a command that might not be supported in your code.

    • console.log--basic logging, which is used to record the basic messages of actions that occur in my code. The format identifier is also supported when the console is called.

    • console.error--errors are logged in the code. I use Console.error in error callbacks for Ajax requests and other places where errors are thrown. Similar to Console.log, this method also includes a stack that tracks where the error is.

    • Console.dir (object)-This handy way to print the contents of a JavaScript object in your console window. Very convenient.

    • Console.group (title)-This allows you to create a set of console logging commands with an optional caption. Meaning you can group similar log messages, such as when a piece of code is responsible for a task.

    • The console.groupcollapsed--is exactly the same as the above method, except that the first is folded and not opened.

    • console.groupend--This allows you to end the group defined above.

    • Console.time (label)--Allows you to measure how long a particular JavaScript code will take to run, in milliseconds. This is especially effective for measuring possible bottleneck methods.

    • Console.timeend (label)-similar to the GroupEnd method, which allows you to stop the timer recording function while the runtime is printed on the console.

    • Copy (String)--this method is available in the Chrome and Firefox consoles, which allows you to copy the contents of a string to the Clipboard. Open the development tool, try it, and it can sometimes be useful.

Understand this

This keyword, which is one of the biggest sources of frustration for JavaScript developers who don't understand how it works. It's really easy to fall into a lot of traps: "This" is the biggest problem, depending on your JavaScript structure.

In a more traditional programming language This is a reference to the current object instantiated by the class. But JavaScript is not a traditional programming language, so this actually belongs to the object that owns the method.

The simplest way to remember this in JavaScript is to remember its owner, the father. The value of this will always be equal to the owner unless changed by call,apply or bind.

In the following function, this is actually window:

function MyFunction () {

Console.log (This = = = window);

True

}

MyFunction ();

You might think: why is this equal to window when referencing this in a method? If you know the answer, then it's great, but if you don't know, read on and we'll explain why.

When you define a function like above, it is bound to the global window on the global object. Remember what we mentioned above that JavaScript treats this as the object that owns the method, not the current object?

Change the value of this to a new object (not a window) that belongs entirely to itself:

function MyFunction () {

Console.log (This = = = window);

False

}

New MyFunction ();

Code control may condemn what I have just done. Remember, we just touched on the basic concept a little bit. But as you can see, the value of this is no longer a window. Why?

The simplest explanation is when we use the New keyword, we create a completely new context (because of the new keyword), and the new operator creates a completely new object.

In the following example, we will create a fictional API library that has a way to get data from the server. As you can see, we are creating an object called API and adding a method.

Because we've created a new object, something magical has happened. The context switches from the global object to the creation of our API object.

var API = {

Getdata:function () {

Console.log (This = = = window);

False

Console.log (This = = = API);

True

}

};

Api.getdata ();

As you can see, the this value inside the function depends on how it is called. Because the function is called as part of the API's object, the API object is owned by this, so the value of this is it.

Never assume that the value of this is always the same. It changes based on how the function is called, but if you use Bind,this, the value is always equal to the value specified on the Bing method.

For an in-depth reading of this, take a look at this article on Quirksmode. It ran some examples and explained better than I did. Mozilla developer documentation also has some great explanations for "this", along with examples (here).

' Use strict '; ' Use strict ';

Before briefly discussing, using strict mode (which increases in ECMAScript 5) allows you to use stricter JavaScript variables. You should use it when you write any JavaScript and have a good reason for it. JavaScript is a bit tolerant by default when it comes to what you do. When you reference an undeclared variable and try to do something else that you are not aware of as bad, he silently fails, but JavaScript does not tell you.

There is an entire article on this subject in Mozilla developer, and I implore you to read it, because it is more detailed than I am.

How to write various types of loops

You will be surprised to find that I have encountered many developers who do not know how to write the appropriate for. . Loops, nor does it know that other types of loops are written in JavaScript. Being able to traverse an array or object is an essential skill that all JavaScript developers should have.

There is no one-size-fits-all loop, but you should know when you need it and which one you should use. You might be familiar with for and while, but maybe the rest of the list isn't used much.

Different types of loops in javascript:

    • For

    • For: Inch

    • For: Of (added in ES6)

    • Foreach

    • While

    • Do.. While

For: Cycle

The necessary basic loops are what every JavaScript developer needs to know. The For loop is the core, which loops when the statement remains condition 2 equals true.

for (condition 1; condition 2; condition 3) {

Your Code

}

Condition-the execution before the loop begins. Typically you will define a counter value for the iteration and the total length of the array. If you have made the settings beforehand, you can omit them with a semicolon.

Condition-This is the condition that determines the continuation or cessation of the cycle. You will typically compare the current counter value to the total length of the array. This is a true or false value, and if the value equals True, the loop will continue to run. This can be omitted with a semicolon, forcing you to end the loop internally or you can eventually get an infinite loop.

Condition 3– This runs after each iteration of the loop. The most common is the self-increment counter value here (possibly in the case of 99%). This value can also be omitted with a semicolon (for example, to self-increment your loop inside).

For: In loop

The second most important loop that every JavaScript developer should know. It allows you to traverse the properties of an object, which is its key. Let's look at an example, okay?

var person = {first_name: ' Dwayne ', last_name: ' Charrington ', age:27, star_sign: ' Aquarius '};

The below loop would output:

"Dwayne"

"Charrington"

27

"Aquarius"

For (var p in person) {

if (Person.hasownproperty (p)) {

Console.log (Person[p]);

}

}

You may have noticed that I use a method called hasOwnProperty. This method checks whether the object has a specified property directly on its prototype, not an inherited value. If you are in for.. In loops do not use hasOwnProperty, most JavaScript linter will throw an error.

For: of cycles

This is a new feature of ES6, so the browser isn't supporting it very well now. However, by using Transpiler, you can now use it directly.

For. . of loops like for: In, but it iterates only the objects that can be iterated.

var fruits = [' orange ', ' apple ', ' squash ', ' pear '];

for (var fruit of fruits) {

Console.log (fruit);

}

For: The benefit of the cycle is that we can now finally get all the values of an array, such as not having to write a complex for loop, creating an index, and using a variable to increment a counter. It can be said to be the simplest way to get a value from an array.

foreach Loop

This is an interesting thing because even if it is a loop, it cannot be considered a traditional loop because there are some limitations when using it.

The Foreach Loop also applies only to arrays, not objects. It has the advantage of not requiring additional variable definitions, so it does not pollute your scope, it is just a method.

A loop of meaning, maybe you don't need to really know is a loop. Always I think it is very useful, it is important that you know your choice when iterating over an array of entries.

var fruits = [' apple ', ' banana ', ' orange ', ' grapes ', ' pear ', ' passionfruit '];

The three values on the callback function is:

element-the element being traversed

Index-the Current index of the item in the array starting at 0

Array-the array being traversed (probably mostly irrelevant)

Fruits.foreach (function (element, index, array) {

Console.log (index, Element);

});

Sometimes you just want to simply walk through an array and get its value, modify them, like jquery gives us the Jquery.each form.

The only downside to foreach is that you can't break the loop. If you want to use ES5 syntax to create a loop, you can use the Array.every, which you can read here.

While loop

A while loop is similar to a for loop, and it accepts only one argument, which is a declaration that equals true or false. So if you remember earlier that we had three conditions in the For loop, it was condition 2.

While loops are often considered to be the fastest type of loops, which is controversial. You can't fail to admit that they look cleaner than other types of loops. In some cases, they can be the fastest type of loops, because they can have less complexity.

In my experience, the fastest while loop is the self-reducing while loop, in which there is a value that is self-reducing until it encounters 0 (the result is false).

var i = 20;

while (i--) {

Console.log (i);

}

Do. . While loop

You won't see do. The. While loop is much more popular to use like a for or while loop. But you should know how the Do While loop is used, even if you never use it.

While loops do not guarantee a certain run. This means that if you provide an expression equal to False for the while loop, it will not run. And Do...while is guaranteed to run at least once.

But that's not the end. The while loop executes its condition before the loop starts, do. The. While execution executes the condition after the loop runs. So why do. The. While is guaranteed to run at least once. The loop runs, the expression is checked, and then continues.

Once again the Mozilla developer documentation has an excellent article on most of the loops, here.

Basic methods and Tasks

Here are some basic ways that you really should know in JavaScript. From using arrays to strings, JavaScript contains a useful repository of methods. In this article we only deal with the methods of handling strings and arrays, without objects or any other type of thing.

If you want to read more about JavaScript processing a variety of data types, Mozilla Developer documentation is a great and concise site to learn more about various approaches.

Obviously some people have a problem with whether you should know all these things, maybe some of them I have overlooked. My memory only extends to the present, but here are some I think most developers should know. Knowing how to manipulate strings efficiently seems to me to be an essential skill.

Working with strings

In addition to using arrays and objects in JavaScript, you will find yourself working with strings probably quite a bit. Even if you really don't use strings (or you don't think you would) understand that the basic method of dealing with strings is something worth doing.

    • String.Replace (regexp | replacethis,replacewith |callback)-Allows you to replace a value with another value, even using a regular expression.

    • String.Concat (' string1 ', ' string2 ', etc ...) -This method allows you to concatenate one or more string values together.

    • String.IndexOf (value)-This method allows you to find the location where the specified value first appears, if no return-1 is found.

    • String.slice (Startindex,endindex)-this method has done its expression of practice. It requires a start index (from 0) and an end index, and returns a new block of strings.

    • String.Split (Separator,limit)-This method splits a string into an array of one or more entries.

    • STRING.SUBSTR (Startindex,length)-this method returns the character in the string from StartIndex to the specified length.

    • String.tolowercase-This method returns the lowercase of the calling string.

    • String.touppercase-This method returns the uppercase of the calling string.

    • The spaces at the beginning and end of the string.trim-call string are deleted.

Working with arrays

During the daily development process, I found myself handling arrays in large quantities. They typically serve as a good way to store data, track status, and use it as a mapping.

I think using arrays to do some basic tasks is a JavaScript developer's basic skill. These things you really should not ask Google again.

    • array.pop-deletes the last element in the array and returns it

    • array.shift-deletes the first element in the array and returns it

    • Array.push (Val1,val2 ...) -Add one or more entries at the tail of an array. The new array length is always returned after the method is run. You can specify multiple comma-separated values.

    • Array.reverse-reverses the order of the array (the first element becomes the last while the last one becomes the first, and so on).

    • Array.Sort ([comparefunction])-Allows you to sort the array by specifying a comparison function that accesses every value in the array that needs to be sorted.

    • Array.join (separator)-this method takes one or more entries in the array and returns a string value that is concatenated by the delimiter. If you do not specify a delimiter, the default value is a comma.

    • Array.indexof (value)-This method can get the position of the first occurrence of the specified value if no return-1 is found.

There are other ways to deal with arrays that are not listed and you should read further here. There are some exciting new ways to add to ES6 that are not listed here, as well as other array methods that apply to specific use cases.

The difference between call and apply

These two methods are easy to misunderstand and scare a lot of developers. Although you can not use call or apply, they are especially handy because they allow you to change the this value in the context when calling a method during run time.

The difference between the two is only subtle, but there is a difference. Using the call method will allow you to provide an infinite comma-delimited argument when calling a function.

Using the Apply method will allow you to invoke a method using an array as the supplied argument. This method is great when you want to use an array as a method to invoke parameters and change the context of this.

If you just want to use the value of an array on a function as a parameter, ES6 provides the spread operator (propagation operator). It does not allow you to change the context of this, but it allows you to use an array value as an argument.

A example using. Call:

function MyFunc () {

Console.log (arguments);

}

Myfunc.call (this, 1, 2, 3, 4, 5);

An example using. Apply:

function MyFunc () {

Console.log (arguments);

}

Myfunc.apply (This, [1, 2, 3, 4, 5]);

The new nature of ES6 means that we need to use call or apply in the future only in very limited circumstances. Thanks to spread operators,arrow functions and the bind function that can be used from ES5.

Familiarity with frames/libraries

This time the biggest competitor of the JavaScript framework family seems to be angularjs,react.js and ember. Of course there are more, but these are the biggest and currently most popular (in my opinion).

As Web applications become more complex, these frameworks and libraries make our development work more comfortable. In 2015, a JavaScript developer should be aware of at least one of the frameworks or libraries outside of jquery, which is not an unreasonable expectation.

Almost any work list you see in the search front-end or JavaScript developer will likely refer to the requirements of one or two frameworks or the skill of adding a sub-item. Please do not fall behind.

node. js

There is no doubt that node. JS has proved its worth, and there is no sign of a halfway failure (unless io.js kills it). Almost all front-end tools are built on top of it, and using node Package Manager, if you have not learned node. js, you should reconsider.

Because the kernel of node. js is JavaScript, the learning curve does not exist if you already have a bit of JavaScript. You'll find that you spend more time on the packages you need to configure your app, rather than learning about node. js.

I personally think that node. JS is a skill that every developer needs to master in 2015. I'm not talking about being overly sophisticated about it, but enough to use it to develop servers, prototypes, tests, and other use cases where node. JS will benefit your workflow.

Of course, there is a node. JS branch called Io.js, which is now exactly the same. Finally, you're just writing JavaScript, although there are some small differences.

Test

There was a time when we didn't test JavaScript code and it wasn't something that many people thought was necessary because we were faced with the fact that things have never been so beautiful or complex to use. This language grew into intrinsic complexity, thanks in part to various front-end frameworks such as ANGULARJS and server-side JavaScript node. js.

As JavaScript develops, we use it to do more things, code expands, and testing becomes important, even if it's not critical. If you don't test your code in 2015, you're wrong.

My favorite test tool is undoubtedly karma. There are many other tools to consider, but karma is especially good for testing angularjs applications. If it's good enough for Angularjs, it's good enough for me.

Tools

In 2015, as a JavaScript developer, it meant knowing how to use task Runners,transpilers, analyzers, and other tools, and we wrote the best JavaScript code with them.

Sometimes the tools bundled in the browser don't always accurately describe what's going on inside your application. Sometimes you need to use professional tools to get more detailed information about how the application works in-house.

Useful tools (if you haven't used them yet); Gulp,webpack and Babeljs. There are a lot of tools here, task runners such as Gulp and Grunt, who are especially helpful for the heavy workflow of modern JavaScript (if you haven't used them yet).

To download a separate JavaScript file, the days that are contained in our pages are gone. This time package manager such as NPM and Bower are used instead of manual download scripts.

We use task runners to merge and compress scripts, and testing using separate tools is often more organized.

With such JavaScript tools, you write isomorphic JavaScript (shared code libraries between the server and the front end).

ES6, aka ECMAScript 6, aka Esnext

Although the browser has a time to go before ECMAScript 6 is supported by most of the good features, we can now use Transpilers to start writing ES6 code.

Be familiar with all the new APIs and methods, strings, arrays and other cool features such as weakmaps,symbols and classes. In 2015, being a developer meant keeping pace with the changes in the JavaScript language.

Especially familiar with the concept of classes. They are just the grammatical sugars on the prototype inheritance (currently), but there are also plans to promote classes in ES7, making them more useful and less grammatical.

Further reading

There's a lot more to learn about JavaScript in-depth than this article, much better and deeper.

    • You might not need jQuery

    • Mozilla developer:javascript Reference & Guide

    • Js:the Right

    • AirBnb ' s Javascript styleguide

Conclusion

There are a lot of things I can keep talking about. Obviously this article is very large and the expectations of modern JavaScript developers are many. This article is really just the tip of the iceberg.

Please do not write this article as a JavaScript developer should know the Creed or final list. But as I've said, there are things that all JavaScript developers should know that this article is my personal idea.

If you have any improvements or found anything that can be extended or supplemented, please comment below and let me know.

Original source: ilikekillnerds.com

Source: Bole Online-CUCR

Links: http://web.jobbole.com/82446/

"Front-end Daquan" Share the Web front-end Related technical articles, tool resources, selected courses, hot information, related positions. Welcome attention.

Number:Frontdev

(Long press, pop-up "identify QR code" to quickly follow)

Read the original

Sweep
Follow the public number

The things that every JavaScript developer should know

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.