Javascript. Swap two variables. How it works? [duplicate] - javascript

This question already has answers here:
javascript variable swapping using arrays
(3 answers)
Closed 8 years ago.
Saw in a single source next:
[param_o,param_got] = [param_got,param_o];
This code swap variables param_o & param_got.But how [param_o,param_got] = [param_got,param_o] works, if [] is new instance of Array in Javascript ?
EDIT
Try checking:
var param_o = 1;
var param_got = 2;
[param_o,param_got] = [param_got,param_o];
console.log(param_o+" "+param_got);
// 2 1

This notation is called destructuring assignment and is part of Javascript 1.7:
Destructuring assignment makes it possible to extract data from arrays
or objects using a syntax that mirrors the construction of array and
object literals.
The object and array literal expressions provide an easy way to create
ad-hoc packages of data. Once you've created these packages of data,
you can use them any way you want to. You can even return them from
functions.
One particularly useful thing you can do with destructuring assignment
is to read an entire structure in a single statement.
The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.
Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.

Related

what is the explanation of this kind of instruction let {max}=Math; [duplicate]

This question already has answers here:
What do curly braces inside of function parameter lists do in es6?
(3 answers)
Closed 2 years ago.
I came accross this line of javascript code
let {max}=Math;
that allows you to do this:
let a=max(1,2) //2
Without using the Math object like this:
Math.max(1,2)
I don't know where to find the documentation of this syntax because all I have is that line of code and not a single clue to help me search on google so anyone knows about this practice ?
This is called Destructuring Assignment and you can find documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
What you see there is called Destructuring assignment.
You'll find plety of examples when you Google for Destructuring assignment JS ;)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Anyway, in this particular case you assign the property max (a function in this case) from Class Math.
This allows you to just call max directly.
Imagine having an object DestructTest with a property x
Then you can get the property x by just typing const {x} = DestructTest
Instead of const propX = DestructTest.x
JavaScript takes care for you to get the wanted property for you if you just ask for the right name ;)
Hope this makes things a bit more clear.
Cheers

Adding custom function to object prototype [duplicate]

This question already has answers here:
ES6 arrow functions not working on the prototype?
(4 answers)
Arrow Functions and This [duplicate]
(5 answers)
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 3 years ago.
I'd like to know how to add a custom function to the array object using prototype.
I called my function get. get takes an index and returns the element from the array with that index. It's pointless i know, but im using it for educational purposes.
So this is how it'd look like using it.
const a = ['1' , '2' , '3'];
a.get(2) -----> returns '3'
This is what i've tried.
Array.prototype.get = index => {
return this[index];
};
let a = ['1','2' ,'3'];
console.log(a.get(1));
This returns undefined to me.
By using arrow function you can't bind "this" so in the context of the prototype this equals to "window".
Try this:
Array.prototype.get = function(index){
return this[index];
};
I would strongly discourage you from extending/overwriting native JavaScript internals. There are many reasons it's a dangerous practice and it will definitely cost you a lot in future, which happened few years ago to one of the well-known JS frameworks, called Prototype:
In April 2010, blogger Juriy 'kangax' Zaytsev (of Prototype Core) described at length the problems that can follow from monkey patching new methods and properties into the objects defined by the W3C DOM.[5] These ideas echo thoughts published in March 2010 by Yahoo! developer Nicholas C. Zakas They have been summarized as follows:
Cross browser issues: host objects are not subject to rules, non-compliant IE DOM behavior, etc.
Chance of name collisions
Performance overhead
More info

how to copy an object over another without the two referencing each other? [duplicate]

This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Closed 5 years ago.
Let's say we got this:
this.myObject = {"id":1};
and we want to store the state of my object as my object original as the following:
this.myObjectORG = this.myObject;
then you go on your business and change props on your object like this
this.myObject.id = 2;
and to your surprise down the road, you realize that
console.log (this.myObjectORG.id) // also reports 2
Well, that's just how JS works & I'm not questioning that.
Is there a way to preserve the state of the myObject so I can do comparisons whether its properties changed since its original state?
At some point I'd like to be able to do something like this
if ( this.myObjectORG.id !== this.myObject.id ) {
// but this condition is never true
}
Does this help:-
An Object.assign method is part of the ECMAScript 2015 (ES6) standard and does exactly what you need.
var this.myObjectORG = Object.assign({}, this.myObject);
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

How does the functions differ from objects in Javascript? [duplicate]

This question already has answers here:
Set document.getElementById to variable
(5 answers)
Closed 5 years ago.
I have this habit of using function id(_id) { return document.getElementById(_id); } as to lessen the work of typing this over and over.
sidenote:
jquery becomes too heavy for small tasks and projects
As I learnt Javascript more I came to know that we can pass around functions just like objects so we can do
var id = document.getElementById;
It seems like both do the exact same thing. However, I am not an expert in Javascript, so could there be any difference internally? and which is the preferred way of using?
Yes, the context is:
const log = console.log;
log("test");
The upper wont work because the context changed, and log must be called on a console object, not on window ( aka without context). However, there are easy workarounds:
const log = console.log.bind(console);
Or you use functions, for example the arrow ones:
const log = (...args) => console.log(...args);

Putting items in JavaScript arrays on arbitrary indices [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are Javascript arrays sparse?
Is the following "safe" in JavaScript? (as in, can be expected to work reliably on all JavaScript engines)
a = [];
a[100] = "hello";
a[100] == "hello"; // should be true
Yes. Arrays in JavaScript are sparse and your code is expected to work in all JavaScript implementations.
You can get into requirements in the section 15.4 of the specification(PDF).
Short summary: array is special object that have length property adjusted when one adds elements at properties with numeric names (like `a[123]="test"). Other methods like join take length into account duuring operations.
Yes, why wouldn't it work? Its perfectly acceptable syntax.
You can even assume
a[100] === "hello"; // will return true

Categories

Resources