javascript - indentation and position of curly brackets [duplicate] - javascript

This question already has answers here:
JavaScript braces on new line or not? [closed]
(9 answers)
Closed 5 years ago.
I was used in this type of convention of indentation and curly brackets placement in college.
function code()
{
if(code)
{
code
}
}
but online tutorials in javascript tells me to do this style instead
function code(){
if(code){
code
}
}
this first one is also my preferred style because it is more clear and understandable. My question is why do I have to follow the second example? is there any advantages??

The official answer is that you can use either, but the practical answer is that it is safer to use the version where the opening curly brace is on the same line as the code block it defines.
In JavaScript, {} is the syntax for an object literal and JavaScript also has automatic semi-colon insertion. This automatic semi-colon insertion can cause functions written with the opening curly-brace on a different line than the function it defines the body of, to execute differently than you would expect. See this for details:
Why do results vary based on curly brace placement?

Mostly preference. I personally prefer the second way, but the only difference is when javascript's automatic semicolon insertion kicks in. There is no difference when dealing with function declarations or if statements.

Related

Validator.js - How to validate Alphanumeric password, in NodeJS? [duplicate]

This question already has answers here:
What do the brackets around the arguments mean when reading documentation for a method? [duplicate]
(3 answers)
Closed 4 years ago.
I am using criso validator.js, of user Input,
but it Eslint is showing error in syntax on this lines
if (!Validator.isAlphanumeric([(data.password,'en-US')])) {
console.log(" Not an alphanumeric");
}
how to properly check user's entered password is Alphanumeric,
I know we can do it using regex but I wanted to do it by using their provided syntax as isAlphanumeric(str [, locale]).
here is their documentation screenshot of code.
The square brackets in the isAlphanumeric(str [, locale]) notation are not related to JavaScript Array literals. Instead, they denote that when calling isAlphanumeric, the first argument str (in your case, data.password) is required, and the second argument locale is optional.
In your case, you do want to pass in a locale. Here is how that would look:
if (!Validator.isAlphanumeric(data.password, 'en-US')) {
console.log("Not an alphanumeric");
}
In technical documentation, square brackets ([]) generally denote that an argument is optional. Tecnhnically this is just a convention (and probably comes from Unix CLI Usage Messages), but in my experience is so widely used that always interpreting square brackets as denoting an optional argument is usually a safe assumption to make.

javascript console.log new feature with 'raw'? [duplicate]

This question already has answers here:
Backticks (`…`) calling a function in JavaScript
(3 answers)
Closed 6 years ago.
I have encounter this example and was completely lost...
const test = (hey) => console.log(hey);
console.log(test `wtf`);
First all this is valid, in the console.log, it appear to be
["wtf", raw: Array[1]]
It's like the function is been executed and with extra raw? can someone please explain?
It's just a Tagged Template Literal. It looks fancy, but there's nothing too special about it. Note, they're part of ES6/ES2015 so you will need to tranpsile them if you plan on supporting older browsers.
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 / ES6 specification.
credit to #karmuran and #deceze
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals
Raw strings
The special raw property, available on the first function argument of tagged template literals, allows you to access the raw strings as they were entered.
function tag(strings, ...values) {
console.log(strings.raw[0]);
// "string text line 1 \n string text line 2"
}
tag`string text line 1 \n string text line 2`;

Does there need to be a semicolon? [duplicate]

This question already has answers here:
Do you recommend using semicolons after every statement in JavaScript?
(11 answers)
Closed 7 years ago.
In the book "Beginning JavaScript" by Jeremy McPeak and Paul Wilton there's a do-while loop example.
var userAge;
do {
userAge = prompt("Please enter your age","")
} while (isNaN(userAge) == true);
and below the author repeats one more time:
userAge = prompt ("Please enter your age","")
There's no semicolon at the end of the statement inside the do {} block. As far as I can remember the author stated that it's considered best to always end any statement with a semicolon although it's not a must in most cases.
Was the omission of ; intentional? It seems so considering that in both the 4th and 5th editions there's no semicolon.
And there's also a repetition of that line below which doesn't contain a semicolon either.
Of course, one might say that it's not even a mistake. What I want to understand is whether the omission of a semicolon is more likely to be a typo or (which is worse) rather was done intentionally. If the latter is true, isn't that a sign of inconsistency?
When writing or editing javascript, the semicolon helps a lot visually.
Depending on your editor, it may not be clear otherwise if you actually have a line break in there (ending the line of code). Instead, your editor may just be wrapping the line visually. So without the semicolon, you can make and overlook errors more easily. For more info:https://www.webmasterworld.com/forum91/521.htm

What is the purpose of a semicolon before an IIFE? [duplicate]

This question already has answers here:
What does the leading semicolon in JavaScript libraries do?
(6 answers)
Closed 9 years ago.
I was checking out the code of has.js and was puzzled by the initial semicolon here:
;(function(g){
// code
}()(this);
As far as I know, it does absolutely nothing. It does not put the function in expression position as () or ! do: (function(){}()) or !function(){}(). It seems to be merely a line ender for an empty line.
What is the purpose of this semicolon? An OCD desire for symmetry between the beginning and end of the IIFE? :)
It's there to prevent any previous code from executing your code as the arguments to a function.
i.e.
mybrokenfunction = function(){
} //no semicolon here
(function(g){
})(this);
will execute mybrokenfunction with your anonymous function as its argument:
mybrokenfunction = function(){}(function(g){})(this);
If you could guarantee that there won't be an unterminated (no semicolon) function before yours, you could omit the starting semicolon, but you can't, so it's just safer to put that extra semicolon in.

What is this kind of variable $variable [duplicate]

This question already has answers here:
Why would a JavaScript variable start with a dollar sign? [duplicate]
(16 answers)
Closed 9 years ago.
I found an JavaScript file in a website using a variable like this:
var $variable
What kind is it?
Thanks, DGM
$ is a regular symbol like any other legal one in JS and can be used as or part of a variable as well:
var $ = {};
It's also the identifier for the jQuery object. So that's why you'll normally see variables named that way that represent jQuery objects:
var $variable = $('#element');
There's also Underscore.js that uses the underscore symbol _ as its root object.
It is a completely normal variable, starting with the dollar sign - which has no special meaning in JavaScript. It is a valid identifier just as like the underscore.
Sometimes, variable names prefixed with $ indicate that they contain an object wrapper created by one of the libraries that use $ as a constructor (for example jQuery); in contrast to a "plain value".
Javascript identifiers must start with a letter, an underscore or a dollar sign. So it is just a variable.
The intended use of the $ sign was for code generators, but some libraries use it for their own purposes.
It is perfectly valid to use $ in javascript variable names. Personally, I try to avoid this as it can be confused with jquery objects or php variables which may have crept into the javascript by mistake.

Categories