I'm trying to make an increment method. This seemingly easy task has stumped me.
An example of what I want:
var x=5;
x.increment();
console.log(x); //6
What I tried to do:
Number.prototype.increment=function(){
this++; //gave me a parser error
};
Numbers are immutable in javascript. when you do console.log(this) you will see it will point to Number whose primitive value is 5(in our case), so you can not change it's value.
What you can do is return incremental value(by doing this + 1) from incremnt and assign it to x like x=x.increment();
Number.prototype.increment = function(){
return this + 1;
}
var x = 5;
x=x.increment();
console.log(x);
this cannot be changed directly. Try this way
Number.prototype.increment = function(){
return this + 1;
}
var x = 5;
x = x.increment(); // x will be 6 here
Hope this helps.
Related
I'm currently learning javascript and I would appreciate some help.
I've been playing around trying to create a program that would multiply two numbers without using the * operator. I already found an easier way to do it than my approach but I'd like to know why the code I wrote doesn't work:
function addToItself(a) {
a = a + a;
return a;
}
function times(b) {
for (count = 0; count < b; count++) {
addToItself(a)
}
return a;
}
function multiply (x, y) {
a = x;
times(y);
}
let output = multiply(5, 2);
alert(output);
Is it not working because the binding "a" in the addToItself function has a local scope and the multiply function can't read it or is it something else?
Thanks a lot in advance!
The issue is with the scope of each variable. In JavaScript, a variable declated within a function is scoped to that function. This means that a variable declared within a function can only be accessed within the function. Scopes are nested, so a variable declared globally is accessible inside a function too, though that's often discouraged.
Additionally, function arguments (such as a in addToItself and b in times) are treated like variables scoped to the function.
I would advise looking at the MDN docs for "scope" and familiarizing yourself with how variables are scoped in JavaScript.
I have included a fixed version of your code is below, for reference:
function addToItself(a) {
// I used a new variable here since reassigning to an argument is discouraged
const twoA = a + a;
return twoA;
}
console.log('5 + 5 = ' + addToItself(5));
function times(value, times) {
let temp = 0;
for (let count = 0; count < times; count++) {
temp += value;
}
return temp;
};
console.log('5 * 5 = ' + times(5, 5));
No you can't read variable inside another function, there are easier way, like
function multiply(x, y) {
var result = 0;
for (var count = 0; count < y; count++) {
result += x
}
return result;
}
console.log("5 * 2 = " + multiply(5, 2));
var sum = 2;
function addFive() {
var sum = sum + 5;
console.log(sum); //why not 7
}
addFive();
Why is it returning NaN instead of 7?
To make things clearer, your code is essentially being read like so:
var sum = 2;
function addFive() {
var sum; // implicitly equal to undefined
sum = sum + 5; // sum = undefined + 5 = NaN
console.log(sum); // NaN
}
addFive();
As you can see, you're redeclaring sum and it is set to undefined. So, when you try and add 2 to undefined you're going to get NaN (Not a Number).
Instead, you can reference your outer sum variable by not redefining it within your function and instead just reassign its value:
var sum = 2;
function addFive() {
sum = sum + 5; // sum = 2 + 5 = 7
console.log(sum); // 7
}
addFive();
You're declaring the variable sum again in the function. This has all to do with scoping in JavaScript.
Take a look at the following article to learn more.
In this case, the local variable (the one that's declared inside the function) gets priority by the JavaScript parser. This behavior's called 'shadowing'. It starts at the innermost scope being executed at the time, and continues until the first match is found, no matter whether there are other variables with the same name in the outer levels or not.
Because you are declared a local variable sum inside the function.
You have to use this.
var sum = 2;
function addFive(){
var sum = this.sum + 5;
console.log(sum);
}
addFive();
In this context, this will refer to the global object (in a browser, window), so the above code is equal to:
var sum = 2;
function addFive(){
var sum = window.sum + 5;
console.log(sum);
}
addFive();
You can read more about this in this SO post or on MDN
I have a variable equal to number, so I want decrease this variable value every second.
in this code it is print the same number over and over, although I have written
(n--)
var x = setInterval(function() {
var n = 50;
console.log(n--);
}, 1000);
my question how I can decrease it?
You could use a IIFE with a closure about the value. Tha advantage is to use a local variable without polluting the global space.
var x = setInterval(function(n) {
return function() {
console.log(n--);
};
}(100), 1000);
And here is one without the need of a global variable but using IIFE:
var x = setInterval(
(startValue => () => {
console.log(startValue--);
})(100),
1000
);
Checkout this: it will stop when x will equals to zero
var x = 100;
var handler = setInterval(function(){
x--;
console.log(x);
if(x === 0)
clearInterval(handler)
} , 1000)
Your code issue is that you put the -- sign after and It should be before(--n) and It also you have declared var n = 50 inside to loop of setInterval, at this way each time that It's executed n variable always is 50, you should to put this varible at the start of yout code.
var n = 50;
var x = setInterval(function() {
console.log(--n);
}, 1000);
I'm working on an ionic 2 project which uses angular 2.
I just have this in mind if there's a way I can create a variable to bind to
another variable(s).
Let's say,
let x = 1;
let y = x;
where y will have the exact value of x even when it changes.
And if it does work, can I also do this?
let x = 1;
let y = 1;
let z = x + 1;
I'd like to know if this is possible or not.
Just had this in mind. Thanks and cheers!
In Angular components and providers this is solved with property accessors:
class SomeService {
x = 1;
get y() {
return this.x;
}
get z() {
return this.x + 1;
}
}
It's not possible to pass scalar value by reference (and there are usually no reasons to do that in Angular).
Javascript does not allow passing reference of the primitive types. So you can achieve this by wrapping them in an object.
let x = {
value: 1,
get z() { return this.value + 1}
}
let y = x;
y.value = 10; // Now x.value is also 10
This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 7 years ago.
Hi I have a snippet of code. I am confused about change of value x1 when I remove non-related part of same code. I searched about it and I came to know that it has to do with hoisting. But the value x1 is still unclear even with hoisting concept for me. Can someone please make me clear on this?
var x = 10;
function main() {
document.write("<br>x1 is " + x);
x = 20;
if (x > 0) {
var x = 30;
document.write("<br>x2 is " + x);
}
var x = 40;
var f = function(x) {
document.write("<br>x3 is " + x);
}
f(50);
}
main();
The output of this code is:
x1 is undefined
x2 is 30
x3 is 50
If I change this code to:
var x = 10;
function main() {
document.write("<br>x1 is " + x);
}
main();
The output is:
x1 is 10
So what is happening here is a common pitfall.
The simplest way to put this is. When you set var x = 30 inside your main function, you are actually redefining the scope that var x = 10 had for use inside this function. This has to do with how Javascript executes and scope.
By defining x inside the function, your scope for x has changed. Below is an example of what I mean and a version of your code that works
Example:
var test = 'test';
function run(){
console.log(test);
var test=1;
}
Your Code Updated:
var x = 10;
function main() {
console.log("<br>x1 is " + x);
x = 20;
if (x > 0) {
x = 30;
console.log("<br>x2 is " + x);
}
x = 40;
var f = function(x) { console.log("<br>x3 is " + x); }
f(50);
}
main();
Good question btw.
Since this is somewhat of a very interesting scope of how Javascript executes, consider the following code and its outputs to get the full idea
var test = 'test';
function run(){
console.log(test);
test=1;
console.log(test);
var test=2;
console.log(test);
}
console.log(test);
run();
console.log(test);
Very interesting to see how this reacts.
All variable and function declarations get "hoisted" or moved to the top of their scope. The undefined value for x is caused because the var x statement gets moved up to the top of main however the assignment = 30 does not.
So, your code will read more like this:
var x = 10; // x is 10
function main() {
var x; // x declaration is "hoisted"
document.write("<br>x1 is" + x); // x1 is undefined
x = 20; // x is 20
if (x > 0) {
x = 30; // x is 30
document.write("<br>x2 is" + x);// x2 is 30
}
x = 40; // x is 40
var f = function(x) { // x is 50
document.write("<br>x3 is" + x);// x3 is 50
}
f(50);
}
main();
You can read more about Hoisting here: JavaScript Scoping and Hoisting