Overwrite anonymous const function in javascript [duplicate] - javascript

This question already has answers here:
delete or override const variables in javascript Harmony / ECMAScript 6
(2 answers)
Closed 3 years ago.
I was trying to figure this out with a friend.
Let's say you have a function like this:
const foo = function(i) { return function(j){ return 2 * j } };
How would I override foo with a different method?
Let's say I want to reuse foo with a different anonymous function that does something like function(j){ return 3 * j; };
How would I do that?
EDIT: I saw this post, but that's for variables. I'm asking specifically about anonymous methods.
EDIT 2: This is a proof of concept, so let's say that foo is a const and I can't turn it into a let

const is used for constants, so it's not for overriding.
If you want to override your variable, use let or var
const constantFunction = x => x + 1;
let variableFunction = x => x + 2;
try {
variableFunction = x => x + 3;
console.log('Re-assigning to a variable: DONE');
} catch(e) {
console.log('Error while re-assigning to a variable');
}
try {
constantFunction = x => x + 3;
console.log('Re-assigning to a constant: DONE');
} catch(e) {
console.log('Error while re-assigning to a constant');
}

Related

Is there a way to call a function through using a string that matches its name? [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 2 years ago.
This is what I have attempted, and may give a better gist of the question I'm trying to ask:
var x = "run";
var y = "Function";
var xy = x + y;
function runFunction() {
console.log("Function has been called.");
}
xy();
What am I doing wrong here?
You could use eval(), but don't. Instead, store your functions in an object:
const functions = {
greetingOne: () => console.log("Hello!"),
anotherGreeting: () => console.log("Hi there!");
};
const f = "greetingOne";
functions[f]();
It is possible if the function lives on an object.
const obj = {
runFunction: function() {console.log('hello')}
}
var x = "run";
var y = "Function";
var xy = x + y;
obj[xy]();
You can call eval that run string as Javascript code
function runFunction() {
console.log("Function has been called.");
}
functionName = 'runFunction'
eval(functionName + '()');
All global functions stores in window object.
let first = "first";
let second = "Second";
let xy = first+second;
function firstSecond() {
return "Hello World";
}
console.log(window[xy]());

When and why to use these various Java Script function declaration formats? [duplicate]

This question already has answers here:
Export const arrow function or basic function?
(1 answer)
What are the advantages/disadvantages for creating a top level function in ES6 with arrows or without?
(2 answers)
Closed 4 years ago.
What are the differences between the following function declaration formats?
When is it more correct to use which?
From a beginner's perspective, and a high level (non-deep) point of view, they all three appear to work the same - hence it makes things feel confusing and demands the question.
1.
const counter1 = function(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
2.
function counter2(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
3.
const counter3 = (num) => {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
All of them appear to behave the same.
There are more than a few differences between your three examples actually.
So, for one, you have to be careful using const for your function declarations.
counter1(5); // counter1 is undefined, this will fail
const counter1 = function(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
Whereas the function will be hoisted and available for use (Edit: technically let and const are also hoisted, but they aren't initialized so you cannot access them before they are declared, more info here.
counter2(5); // works fine
function counter2(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
Also note that const prohibits reassigning the variable, so you couldn't go say const counter1 = {} later down the line, whereas you could feasibly do so with the function example.
As far as the difference between function(num) { versus (num) => {, well in your example it makes no difference. But there are some differences... for example
const thisWillFail = () => {
console.log(arguments.length);
};
const thisWorks = function() {
console.log(arguments.length);
};
If you're unfamiliar with the arguments object, you can find info here.

Javascript Function Call [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 6 years ago.
The question is really simple but i searched everywhere couldn't get an answer.
add();
function add()
{
//function code here
}
The above code works in JavaScript even though function call is before function definition but wouldn't work in language such as C or C++. Could anyone tell me why?
It's known as hoisting, and it's definitely a trap for beginners!
Basically, if you take this code:
var x = 21;
var y = add10(x);
function add10(n) { return n + 10; }
after hoisting, it is evaluated like this:
function add10(n) { return n + 10; }
var x;
var y;
x = 21;
y = add10(x);
Because the declarations are separated from the definitions, and "hoisted" to the top.
Funnily enough, this would fail:
var x = 21;
var y = add10(x);
var add10 = function (n) { return n + 10; }
because it is evaluated like this:
var x;
var y;
var add10;
x = 21;
y = add10(x); // add10 is not a function (yet...)!
add10 = function (n) { return n + 10; }
It's called hoisting.
The javascript engine first looks for function declarations and 'hoists' them to the top before your actual code starts running.
Here's the documentation: http://www.w3schools.com/js/js_hoisting.asp

Method error: Method name not defined [duplicate]

This question already has answers here:
Javascript: Do I need to put this.var for every variable in an object?
(6 answers)
Closed 7 years ago.
Why isn't this code working? I'm trying to use the method to add up the properties and then assign the added up properties to its own value.
function howLongILivedSomewhere(college, home1, home2) {
this.birthHome = 18;
this.college = college;
this.home1 = home1;
this.home2 = home2;
this.calcYearsAlive = function() {
return birthHome + college + home1 +home2;
};
this.yearsAlive = calcYearsAlive();
}
var me = new howLongILivedSomewhere(4, 2, 3);
console.log(me);
You missed this keyword during your method / property call. Try like below.
function howLongILivedSomewhere(college, home1, home2) {
this.birthHome = 18;
this.college = college;
this.home1 = home1;
this.home2 = home2;
this.calcYearsAlive = function() {
return this.birthHome + this.college + this.home1 + this.home2;
};
this.yearsAlive = this.calcYearsAlive();
}
var me = new howLongILivedSomewhere(4, 2, 3);
console.log(me.yearsAlive); // output: 27
What is this keyword?
A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
How does "this" keyword work within a function?
Update the constructor to:
function howLongILivedSomewhere(college, home1, home2) {
this.birthHome = 18;
this.college = college;
this.home1 = home1;
this.home2 = home2;
this.calcYearsAlive = function() {
return this.birthHome + this.college + this.home1 + this.home2;
};
this.yearsAlive = this.calcYearsAlive();
}
var me = new howLongILivedSomewhere(4, 2, 3);
console.log(me);
Use this keyword when you need to access the object properties (see here more details).

How does global variables in JavaScript work? [duplicate]

This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 8 years ago.
I m a newbie to javascript. I usually program in Java. I am confused by this following code snippet.
<script>
x = "foo";
function bar(p){
if (p){
document.writeln("x = " + x);
} else {
var x = "baz";
}
}
bar("baz");
</script>
When I run the above code snipped its printing
x = undefined
Why does it print undefined, since x is a global variable it should print foo right ? Can anyone explain ?
since x is a global variable it should print foo right
It would if it wasn't shadowed by the var x = "baz"; declaration further up in your function; due to hoisting it will execute the function as if you wrote
function bar(p){
var x; // = undefined
if (p){
document.writeln("x = " + x);
} else {
x = "baz";
}
}
To make the code do what you want, you could simply write x = "baz"; instead of var x = "baz";.
try this output is x = foo
var x="foo";
function bar(p){
if (p){
document.writeln("x = " + x);
} else {
x = "baz";
}
}
bar("baz");

Categories