2

I'm writing my first ever jquery dependant plugin.

My question is can default parameters be variable like so:

var s = 400,
    m = 500,
    l = 700,
    xl = 960;

function breakpoints(s = s, m = m, l = l, xl = xl) {
  return {
    s: s,
    m: m,
    l: l,
    xl: xl
  };
};

When using console.log(s, m, l, xl); inside my initial breakpoints() declaration I get the error:

s is not defined

Thanks in advance for your help.

2
  • be on the look out for function hoisting. Commented Aug 31, 2017 at 13:00
  • So it's just a typo? Commented Aug 31, 2017 at 13:02

3 Answers 3

5

ES6/ES2015 support default values on arguments, so your code will work so long as the browser supports those standards.

That being said you need to give the outer/inner variables different names, otherwise they won't be available where you attempt to use them. Try this:

var s = 400,
    m = 500,
    l = 700,
    xl = 960;

function breakpoints(_s = s, _m = m, _l = l, _xl = xl) {
  return {
    s: _s,
    m: _m,
    l: _l,
    xl: _xl
  };
};

console.log(breakpoints());

Sign up to request clarification or add additional context in comments.

6 Comments

Duplicating variable names in different scopes is a bit of an anti-pattern - I recommend using something like eslint to help flag it up.
This answers my question @Rory. Will accept when I can. Thank you.
@DanMad no problem, glad to help
@Rory I'm agreeing with you and suggesting further steps DanMad might take to help reduce the problem in general. Sorry for the confusion.
Ahhh got you :) I'll delete my comment to avoid confusion for any future visitors
|
2

You can use default parameters starting from ES6/ES2015. The only issue is that you need to rename your input parameters.

var s = 400,
    m = 500,
    l = 700,
    xl = 960;

function breakpoints(_s = s, _m = m, _l = l, _xl = xl) {
  return {
    s: _s,
    m: _m,
    l: _l,
    xl: _xl
  };
};

console.log(breakpoints());

Comments

1

var s = 400,
    m = 500,
    l = 700,
    xl = 960;

console.log(breakpoints(s,m,l,xl));

function breakpoints(s, m, l, xl) {
  return {
    s: s,
    m: m,
    l: l,
    xl: xl
  };
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.