Default Parameter Value in Arrow Function
Asked Answered
C

3

12

I'm new to ES6 Javascript which means i'm exploring it. I like the arrow function and default parameter feature from ES6 which is mentioned in the below site.

http://es6-features.org/#ExpressionBodies
http://es6-features.org/#DefaultParameterValues

Below is my code snippet of ES6 and i have tested this in Chrome 47. I'm trying to give default parameter value for my arrow function which is currently throwing error like

<script type="text/javascript">
  'use strict';
  var greet = (name = 'Venkat') => (console.log('Hi ' + name + '!'));
  greet(); // expected output: Venkat
  greet('Venkatraman'); // expected output: Venkatraman
</script>

Let me know whether its possible, if so, explain with solution and what i'm doing wrong here.

Chromophore answered 18/12, 2015 at 11:0 Comment(3)
Chrome 47 doesn't support default parameters yet (48 does, albeit behind an experimental flag). Your code is valid ES6, so Babel works just fine.Glutenous
provide simple babeljs setup for transpile this codeChromophore
Very very very similar to this question, which has an answer that may be more helpful: https://mcmap.net/q/1010669/-optional-parameter-in-arrow-function/176877Beatup
S
10

No, that's not possible (yet, I suppose). What you can do though:

var greet = name => console.log('Hi ' + (name || 'Venkat') + '!');
greet(); // output: Venkat
greet('Venkatraman'); // output: Venkatraman

Try it here

[jan 2018] The default parameter value is now supported in all major browsers I suppose

Salvidor answered 18/12, 2015 at 11:11 Comment(2)
Thanks for your solution. what happens if i have 4 variables inside the function. this will increase more lines of code.Chromophore
Yep. We'll have to live with it untill there's full support for default parameter valuesSalvidor
P
1

It seems it support only in Firefox

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

Perreault answered 18/12, 2015 at 11:14 Comment(1)
Yes you are right. i tested the code. its working ! my plan is to learn and implement browser compatible snippet for the above problem !Chromophore
L
0

From todays view it is indeed possible - I don't know if it was back then.

The syntax is the following:

const arrowfunctionidentifier = (parameter = defaultValue) => {<content of the function>}

I mean it is basically the same as yours but with curly braces for the function body. Maybe this is the critical difference?

Cheers

Edit: I added a little snipped, for testing purposes :)

const greeting = (user = 'stranger') => {
  console.log(`Greetings! ${user}`);
};

greeting();
greeting('mwannags');
Lugo answered 28/7, 2023 at 16:16 Comment(1)
See the first comment on the question - yes, the problem was that it was not implemented yet in all environments in 2015.Desdamonna

© 2022 - 2024 — McMap. All rights reserved.